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

feat(ssr): When available, leave process.env. accessible in SSR #4192

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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>
}
57 changes: 37 additions & 20 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,46 @@ 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,
const processEnv = {
'process.env.': `({}).`,
'global.process.env.': `({}).`,
'globalThis.process.env.': `({}).`
}

const pattern = new RegExp(
'(?<!\\.)\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
')\\b',
'g'
)
function generatePattern(
ssr: boolean
): [Record<string, string | undefined>, RegExp] {
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,
...(ssr ? {} : processEnv)
}

const pattern = new RegExp(
'(?<!\\.)\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
')\\b',
'g'
)

return [replacements, pattern]
}

const defaultPattern = generatePattern(false)
const ssrPattern = generatePattern(true)

return {
name: 'vite:define',
Expand All @@ -73,6 +88,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