Skip to content

Commit 9465ae1

Browse files
authored
fix(define): replace optional values (#20338)
1 parent 64121c2 commit 9465ae1

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed

packages/vite/src/node/plugins/define.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const nonJsRe = /\.json(?:$|\?)/
1010
const isNonJsRequest = (request: string): boolean => nonJsRe.test(request)
1111
const importMetaEnvMarker = '__vite_import_meta_env__'
1212
const importMetaEnvKeyReCache = new Map<string, RegExp>()
13+
const escapedDotRE = /(?<!\\)\\./g
1314

1415
export function definePlugin(config: ResolvedConfig): Plugin {
1516
const isBuild = config.command === 'build'
@@ -91,7 +92,12 @@ export function definePlugin(config: ResolvedConfig): Plugin {
9192
patternKeys.push('import.meta.env', 'import.meta.hot')
9293
}
9394
const pattern = patternKeys.length
94-
? new RegExp(patternKeys.map(escapeRegex).join('|'))
95+
? new RegExp(
96+
patternKeys
97+
// replace `\.` (ignore `\\.`) with `\??\.` to match with `?.` as well
98+
.map((key) => escapeRegex(key).replaceAll(escapedDotRE, '\\??\\.'))
99+
.join('|'),
100+
)
95101
: null
96102

97103
return [define, pattern, importMetaEnvVal] as const

playground/define/__tests__/define.spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,9 @@ test('replace constants on import.meta.env when it is a invalid json', async ()
109109
),
110110
).toBe('true')
111111
})
112+
113+
test('optional values are detected by pattern properly', async () => {
114+
expect(await page.textContent('.optional-env')).toBe(
115+
JSON.parse(defines['process.env.SOMEVAR']),
116+
)
117+
})

playground/define/index.html

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@ <h2>Define undefined constants on import.meta.env when it's a invalid json</h2>
7272
</p>
7373
</section>
7474

75+
<h2>Optional values are detected by pattern properly</h2>
76+
<p>
77+
process?.env?.SOMEVAR
78+
<code class="optional-env"></code>
79+
</p>
80+
7581
<script>
7682
// inject __VITE_SOME_IDENTIFIER__ to test if it's replaced
7783
window.__VITE_SOME_IDENTIFIER__ = true
@@ -154,6 +160,9 @@ <h2>Define undefined constants on import.meta.env when it's a invalid json</h2>
154160
'.replace-undefined-constants-on-import-meta-env .import-meta-env-SOME_IDENTIFIER',
155161
`${import.meta.env.SOME_IDENTIFIER}`,
156162
)
163+
164+
import optionalEnv from './optional-env.js'
165+
text('.optional-env', optionalEnv)
157166
</script>
158167

159168
<style>

playground/define/optional-env.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// separate file to test pattern filter
2+
export default process?.env?.SOMEVAR

0 commit comments

Comments
 (0)