Skip to content

Commit 416f190

Browse files
committed
feat(plugin-legacy): inject import.meta.env.LEGACY
1 parent 603d57e commit 416f190

File tree

7 files changed

+88
-4
lines changed

7 files changed

+88
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
import { isBuild } from '../../testUtils'
2+
13
test('should work', async () => {
24
expect(await page.textContent('#app')).toMatch('Hello')
35
})
6+
7+
test('import.meta.env.LEGACY', async () => {
8+
expect(await page.textContent('#env')).toMatch(isBuild ? 'true' : 'false')
9+
})

packages/playground/legacy/index.html

+1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
<h1 id="app"></h1>
2+
<div id="env"></div>
23
<script type="module" src="./main.js"></script>

packages/playground/legacy/main.js

+4
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,7 @@ async function run() {
44
}
55

66
run()
7+
8+
document.getElementById('env').textContent = `is legacy: ${
9+
import.meta.env.LEGACY
10+
}`

packages/playground/legacy/package.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,5 @@
1010
},
1111
"devDependencies": {
1212
"@vitejs/plugin-legacy": "^1.0.0"
13-
},
14-
"dependencies": {}
13+
}
1514
}

packages/plugin-legacy/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ By default, this plugin will:
1212

1313
- Inject `<script nomodule>` tags into generated HTML to conditionally load the polyfills and legacy bundle only in browsers without native ESM support.
1414

15+
- Inject the `import.meta.env.LEGACY` env variable, which will only be `true` in the legacy production build, and `false` in all other cases. (requires `vite@^2.0.0-beta.69`)
16+
1517
## Usage
1618

1719
```js

packages/plugin-legacy/index.js

+73-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
const path = require('path')
33
const { createHash } = require('crypto')
44
const { build } = require('vite')
5+
const MagicString = require('magic-string').default
56

67
// lazy load babel since it's not used during dev
78
let babel
@@ -17,6 +18,8 @@ const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("scrip
1718
const legacyEntryId = 'vite-legacy-entry'
1819
const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`
1920

21+
const legacyEnvVarMarker = `__VITE_IS_LEGACY__`
22+
2023
/**
2124
* @param {import('.').Options} options
2225
* @returns {import('vite').Plugin[]}
@@ -184,6 +187,28 @@ function viteLegacyPlugin(options = {}) {
184187
// analyze and record modern polyfills
185188
detectPolyfills(raw, { esmodules: true }, modernPolyfills)
186189
}
190+
191+
if (raw.includes(legacyEnvVarMarker)) {
192+
const re = new RegExp(`"${legacyEnvVarMarker}"`, 'g')
193+
if (config.build.sourcemap) {
194+
const s = new MagicString(raw)
195+
let match
196+
while ((match = re.exec(raw))) {
197+
s.overwrite(
198+
match.index,
199+
match.index + legacyEnvVarMarker.length + 2,
200+
`false`
201+
)
202+
}
203+
return {
204+
code: s.toString(),
205+
map: s.generateMap({ hires: true })
206+
}
207+
} else {
208+
return raw.replace(re, `false`)
209+
}
210+
}
211+
187212
return null
188213
}
189214

@@ -210,7 +235,10 @@ function viteLegacyPlugin(options = {}) {
210235
// preset so we can catch the injected import statements...
211236
[
212237
() => ({
213-
plugins: [recordAndRemovePolyfillBabelPlugin(legacyPolyfills)]
238+
plugins: [
239+
recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
240+
replaceLegacyEnvBabelPlugin()
241+
]
214242
})
215243
],
216244
[
@@ -339,7 +367,37 @@ function viteLegacyPlugin(options = {}) {
339367
}
340368
}
341369

342-
return [legacyGenerateBundlePlugin, legacyPostPlugin]
370+
let envInjectionFaled = false
371+
/**
372+
* @type {import('vite').Plugin}
373+
*/
374+
const legacyEnvPlugin = {
375+
name: 'legacy-env',
376+
377+
config(_, env) {
378+
if (env) {
379+
return {
380+
define: {
381+
'import.meta.env.LEGACY':
382+
env.command === 'serve' ? false : legacyEnvVarMarker
383+
}
384+
}
385+
} else {
386+
envInjectionFaled = true
387+
}
388+
},
389+
390+
configResolved(config) {
391+
if (envInjectionFaled) {
392+
config.logger.warn(
393+
`[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due ` +
394+
`to incompatible vite version (requires vite@^2.0.0-beta.69).`
395+
)
396+
}
397+
}
398+
}
399+
400+
return [legacyGenerateBundlePlugin, legacyPostPlugin, legacyEnvPlugin]
343401
}
344402

345403
/**
@@ -488,6 +546,19 @@ function recordAndRemovePolyfillBabelPlugin(polyfills) {
488546
})
489547
}
490548

549+
function replaceLegacyEnvBabelPlugin() {
550+
return ({ types: t }) => ({
551+
name: 'vite-replace-env-legacy',
552+
visitor: {
553+
StringLiteral(path) {
554+
if (path.node.value === legacyEnvVarMarker) {
555+
path.replaceWith(t.booleanLiteral(true))
556+
}
557+
}
558+
}
559+
})
560+
}
561+
491562
module.exports = viteLegacyPlugin
492563

493564
viteLegacyPlugin.default = viteLegacyPlugin

packages/plugin-legacy/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"dependencies": {
2828
"@babel/standalone": "^7.12.12",
2929
"core-js": "^3.8.2",
30+
"magic-string": "^0.25.7",
3031
"regenerator-runtime": "^0.13.7",
3132
"systemjs": "^6.8.3"
3233
},

0 commit comments

Comments
 (0)