Skip to content

Commit

Permalink
fix: cannot reassign process.env.NODE_ENV in ssr (#6989)
Browse files Browse the repository at this point in the history
  • Loading branch information
poyoho committed Feb 19, 2022
1 parent 12be4d2 commit 983feb2
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions packages/vite/src/node/plugins/define.ts
Expand Up @@ -42,9 +42,11 @@ export function definePlugin(config: ResolvedConfig): Plugin {

function generatePattern(
ssr: boolean
): [Record<string, string | undefined>, RegExp] {
): [Record<string, string | undefined>, RegExp | null] {
const processEnv: Record<string, string> = {}
if (!ssr || config.ssr?.target === 'webworker') {
const isNeedProcessEnv = !ssr || config.ssr?.target === 'webworker'

if (isNeedProcessEnv) {
Object.assign(processEnv, {
'process.env.': `({}).`,
'global.process.env.': `({}).`,
Expand All @@ -53,24 +55,27 @@ export function definePlugin(config: ResolvedConfig): Plugin {
}

const replacements: Record<string, string> = {
...processNodeEnv,
...(isNeedProcessEnv ? processNodeEnv : {}),
...userDefine,
...importMetaKeys,
...processEnv
}

const pattern = new RegExp(
// Do not allow preceding '.', but do allow preceding '...' for spread operations
'(?<!(?<!\\.\\.)\\.)\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
// prevent trailing assignments
')\\b(?!\\s*?=[^=])',
'g'
)
const replacementsKeys = Object.keys(replacements)
const pattern = replacementsKeys.length
? new RegExp(
// Do not allow preceding '.', but do allow preceding '...' for spread operations
'(?<!(?<!\\.\\.)\\.)\\b(' +
replacementsKeys
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
// prevent trailing assignments
')\\b(?!\\s*?=[^=])',
'g'
)
: null

return [replacements, pattern]
}
Expand Down Expand Up @@ -98,6 +103,10 @@ export function definePlugin(config: ResolvedConfig): Plugin {

const [replacements, pattern] = ssr ? ssrPattern : defaultPattern

if (!pattern) {
return null
}

if (ssr && !isBuild) {
// ssr + dev, simple replace
return code.replace(pattern, (_, match) => {
Expand Down

0 comments on commit 983feb2

Please sign in to comment.