Skip to content

Commit

Permalink
fix(define): should not stringify vite internal env
Browse files Browse the repository at this point in the history
  • Loading branch information
sun0day committed Feb 20, 2023
1 parent 5f7f5dc commit 55221ad
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { isHTMLRequest } from './html'
const nonJsRe = /\.json(?:$|\?)/
const metaEnvRe = /import\.meta\.env\.(.+)/
const isNonJsRequest = (request: string): boolean => nonJsRe.test(request)
const internalEnvs = ['__VITE_IS_LEGACY__']

export function definePlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
Expand Down Expand Up @@ -56,9 +57,14 @@ export function definePlugin(config: ResolvedConfig): Plugin {
for (const key in env) {
importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(env[key])
}

Object.assign(importMetaFallbackKeys, {
'import.meta.env.': `({}).`,
'import.meta.env': JSON.stringify(env),
// make sure vite internal env won't be stringify
'import.meta.env': JSON.stringify(env).replaceAll(
new RegExp(`"(${internalEnvs.join('|')})"`, 'g'),
'$1',
),
})
}

Expand Down
1 change: 1 addition & 0 deletions playground/legacy/__tests__/legacy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ test('import.meta.env.LEGACY', async () => {
isBuild ? 'true' : 'false',
true,
)
await untilUpdated(() => page.textContent('#env-equal'), 'true', true)
})

// https://github.com/vitejs/vite/issues/3400
Expand Down
1 change: 1 addition & 0 deletions playground/legacy/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<h1 id="app"></h1>
<div id="env"></div>
<div id="env-equal"></div>
<div id="iterators"></div>
<div id="features-after-corejs-3"></div>
<div id="async-generator"></div>
Expand Down
3 changes: 3 additions & 0 deletions playground/legacy/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ if (import.meta.env.LEGACY) {

text('#env', `is legacy: ${isLegacy}`)

const metaEnvObj = import.meta.env
text('#env-equal', import.meta.env.LEGACY === metaEnvObj.LEGACY)

// Iterators
text('#iterators', [...new Set(['hello'])].join(''))

Expand Down

0 comments on commit 55221ad

Please sign in to comment.