Skip to content

Commit

Permalink
feat(plugin-legacy): inject import.meta.env.LEGACY
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Feb 11, 2021
1 parent 603d57e commit 416f190
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 4 deletions.
6 changes: 6 additions & 0 deletions packages/playground/legacy/__tests__/legacy.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
import { isBuild } from '../../testUtils'

test('should work', async () => {
expect(await page.textContent('#app')).toMatch('Hello')
})

test('import.meta.env.LEGACY', async () => {
expect(await page.textContent('#env')).toMatch(isBuild ? 'true' : 'false')
})
1 change: 1 addition & 0 deletions packages/playground/legacy/index.html
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
<h1 id="app"></h1>
<div id="env"></div>
<script type="module" src="./main.js"></script>
4 changes: 4 additions & 0 deletions packages/playground/legacy/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ async function run() {
}

run()

document.getElementById('env').textContent = `is legacy: ${
import.meta.env.LEGACY
}`
3 changes: 1 addition & 2 deletions packages/playground/legacy/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,5 @@
},
"devDependencies": {
"@vitejs/plugin-legacy": "^1.0.0"
},
"dependencies": {}
}
}
2 changes: 2 additions & 0 deletions packages/plugin-legacy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ By default, this plugin will:

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

- 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`)

## Usage

```js
Expand Down
75 changes: 73 additions & 2 deletions packages/plugin-legacy/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const path = require('path')
const { createHash } = require('crypto')
const { build } = require('vite')
const MagicString = require('magic-string').default

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

const legacyEnvVarMarker = `__VITE_IS_LEGACY__`

/**
* @param {import('.').Options} options
* @returns {import('vite').Plugin[]}
Expand Down Expand Up @@ -184,6 +187,28 @@ function viteLegacyPlugin(options = {}) {
// analyze and record modern polyfills
detectPolyfills(raw, { esmodules: true }, modernPolyfills)
}

if (raw.includes(legacyEnvVarMarker)) {
const re = new RegExp(`"${legacyEnvVarMarker}"`, 'g')
if (config.build.sourcemap) {
const s = new MagicString(raw)
let match
while ((match = re.exec(raw))) {
s.overwrite(
match.index,
match.index + legacyEnvVarMarker.length + 2,
`false`
)
}
return {
code: s.toString(),
map: s.generateMap({ hires: true })
}
} else {
return raw.replace(re, `false`)
}
}

return null
}

Expand All @@ -210,7 +235,10 @@ function viteLegacyPlugin(options = {}) {
// preset so we can catch the injected import statements...
[
() => ({
plugins: [recordAndRemovePolyfillBabelPlugin(legacyPolyfills)]
plugins: [
recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
replaceLegacyEnvBabelPlugin()
]
})
],
[
Expand Down Expand Up @@ -339,7 +367,37 @@ function viteLegacyPlugin(options = {}) {
}
}

return [legacyGenerateBundlePlugin, legacyPostPlugin]
let envInjectionFaled = false
/**
* @type {import('vite').Plugin}
*/
const legacyEnvPlugin = {
name: 'legacy-env',

config(_, env) {
if (env) {
return {
define: {
'import.meta.env.LEGACY':
env.command === 'serve' ? false : legacyEnvVarMarker
}
}
} else {
envInjectionFaled = true
}
},

configResolved(config) {
if (envInjectionFaled) {
config.logger.warn(
`[@vitejs/plugin-legacy] import.meta.env.LEGACY was not injected due ` +
`to incompatible vite version (requires vite@^2.0.0-beta.69).`
)
}
}
}

return [legacyGenerateBundlePlugin, legacyPostPlugin, legacyEnvPlugin]
}

/**
Expand Down Expand Up @@ -488,6 +546,19 @@ function recordAndRemovePolyfillBabelPlugin(polyfills) {
})
}

function replaceLegacyEnvBabelPlugin() {
return ({ types: t }) => ({
name: 'vite-replace-env-legacy',
visitor: {
StringLiteral(path) {
if (path.node.value === legacyEnvVarMarker) {
path.replaceWith(t.booleanLiteral(true))
}
}
}
})
}

module.exports = viteLegacyPlugin

viteLegacyPlugin.default = viteLegacyPlugin
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-legacy/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"dependencies": {
"@babel/standalone": "^7.12.12",
"core-js": "^3.8.2",
"magic-string": "^0.25.7",
"regenerator-runtime": "^0.13.7",
"systemjs": "^6.8.3"
},
Expand Down

0 comments on commit 416f190

Please sign in to comment.