Skip to content
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
8 changes: 7 additions & 1 deletion packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const nonJsRe = /\.json(?:$|\?)/
const isNonJsRequest = (request: string): boolean => nonJsRe.test(request)
const importMetaEnvMarker = '__vite_import_meta_env__'
const importMetaEnvKeyReCache = new Map<string, RegExp>()
const escapedDotRE = /(?<!\\)\\./g

export function definePlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
Expand Down Expand Up @@ -91,7 +92,12 @@ export function definePlugin(config: ResolvedConfig): Plugin {
patternKeys.push('import.meta.env', 'import.meta.hot')
}
const pattern = patternKeys.length
? new RegExp(patternKeys.map(escapeRegex).join('|'))
? new RegExp(
patternKeys
// replace `\.` (ignore `\\.`) with `\??\.` to match with `?.` as well
.map((key) => escapeRegex(key).replaceAll(escapedDotRE, '\\??\\.'))
.join('|'),
)
: null

return [define, pattern, importMetaEnvVal] as const
Expand Down
6 changes: 6 additions & 0 deletions playground/define/__tests__/define.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,9 @@ test('replace constants on import.meta.env when it is a invalid json', async ()
),
).toBe('true')
})

test('optional values are detected by pattern properly', async () => {
expect(await page.textContent('.optional-env')).toBe(
JSON.parse(defines['process.env.SOMEVAR']),
)
})
9 changes: 9 additions & 0 deletions playground/define/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ <h2>Define undefined constants on import.meta.env when it's a invalid json</h2>
</p>
</section>

<h2>Optional values are detected by pattern properly</h2>
<p>
process?.env?.SOMEVAR
<code class="optional-env"></code>
</p>

<script>
// inject __VITE_SOME_IDENTIFIER__ to test if it's replaced
window.__VITE_SOME_IDENTIFIER__ = true
Expand Down Expand Up @@ -154,6 +160,9 @@ <h2>Define undefined constants on import.meta.env when it's a invalid json</h2>
'.replace-undefined-constants-on-import-meta-env .import-meta-env-SOME_IDENTIFIER',
`${import.meta.env.SOME_IDENTIFIER}`,
)

import optionalEnv from './optional-env.js'
text('.optional-env', optionalEnv)
</script>

<style>
Expand Down
2 changes: 2 additions & 0 deletions playground/define/optional-env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// separate file to test pattern filter
export default process?.env?.SOMEVAR