Skip to content

Commit

Permalink
fix(ssr): dont transform process.env. in ssr (#5404)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Oct 28, 2021
1 parent 484aad5 commit 1140981
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 24 deletions.
9 changes: 9 additions & 0 deletions packages/playground/ssr-react/__tests__/ssr-react.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import fetch from 'node-fetch'

const url = `http://localhost:${port}`

test('/env', async () => {
await page.goto(url + '/env')
expect(await page.textContent('h1')).toMatch('default message here')

// raw http request
const envHtml = await (await fetch(url + '/env')).text()
expect(envHtml).toMatch('API_KEY_qwertyuiop')
})

test('/about', async () => {
await page.goto(url + '/about')
expect(await page.textContent('h1')).toMatch('About')
Expand Down
2 changes: 2 additions & 0 deletions packages/playground/ssr-react/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const express = require('express')

const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD

process.env.MY_CUSTOM_SECRET = 'API_KEY_qwertyuiop'

async function createServer(
root = process.cwd(),
isProd = process.env.NODE_ENV === 'production'
Expand Down
7 changes: 7 additions & 0 deletions packages/playground/ssr-react/src/pages/Env.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Env() {
let msg = 'default message here'
try {
msg = process.env.MY_CUSTOM_SECRET || msg
} catch {}
return <h1>{msg}</h1>
}
70 changes: 46 additions & 24 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ import { isCSSRequest } from './css'
export function definePlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'

const processNodeEnv: Record<string, string> = {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
'global.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
'globalThis.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
)
}

const userDefine: Record<string, string> = {}
for (const key in config.define) {
const val = config.define[key]
Expand All @@ -30,32 +40,42 @@ export function definePlugin(config: ResolvedConfig): Plugin {
})
}

const replacements: Record<string, string | undefined> = {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
'global.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
'globalThis.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
...userDefine,
...importMetaKeys,
'process.env.': `({}).`,
'global.process.env.': `({}).`,
'globalThis.process.env.': `({}).`
function generatePattern(
ssr: boolean
): [Record<string, string | undefined>, RegExp] {
const processEnv: Record<string, string> = {}
if (!ssr || config.ssr?.target === 'webworker') {
Object.assign(processEnv, {
'process.env.': `({}).`,
'global.process.env.': `({}).`,
'globalThis.process.env.': `({}).`
})
}

const replacements: Record<string, string> = {
...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('|') +
')\\b',
'g'
)

return [replacements, pattern]
}

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('|') +
')\\b',
'g'
)
const defaultPattern = generatePattern(false)
const ssrPattern = generatePattern(true)

return {
name: 'vite:define',
Expand All @@ -75,6 +95,8 @@ export function definePlugin(config: ResolvedConfig): Plugin {
return
}

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

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

0 comments on commit 1140981

Please sign in to comment.