Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ssr): dont transform process.env. in ssr #5404

Merged
merged 1 commit into from
Oct 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -74,6 +94,8 @@ export function definePlugin(config: ResolvedConfig): Plugin {
return
}

const [replacements, pattern] = ssr ? ssrPattern : defaultPattern
patak-dev marked this conversation as resolved.
Show resolved Hide resolved

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