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: don't escape dash in define regex #9980

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export function definePlugin(config: ResolvedConfig): Plugin {
'(?<![\\p{L}\\p{N}_$]|(?<!\\.\\.)\\.)(' +
replacementsKeys
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
})
.join('|') +
// Mustn't be followed by a char that can be part of an identifier
Expand Down
9 changes: 8 additions & 1 deletion playground/define/__tests__/define.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, test } from 'vitest'
import viteConfig from '../vite.config'
import { page } from '~utils'
import { isBuild, page } from '~utils'

test('string', async () => {
const defines = viteConfig.define
Expand Down Expand Up @@ -44,4 +44,11 @@ test('string', async () => {
expect(await page.textContent('.define-in-dep')).toBe(
defines.__STRINGIFIED_OBJ__
)

// only possible through text replacement in build mode, not with global vars in dev (client/env.ts)
if (isBuild) {
expect(await page.textContent('.key-includes-dash')).toBe(
String(defines['KEY-INCLUDES-DASH'])
)
}
})
3 changes: 3 additions & 0 deletions playground/define/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ <h1>Define</h1>
<p>define variable in html: <code class="exp-define">__EXP__</code></p>
<p>import json: <code class="import-json"></code></p>
<p>define in dep: <code class="define-in-dep"></code></p>
<p>key includes dash: <code class="key-includes-dash"></code></p>

<script type="module">
const __VAR_NAME__ = true // ensure define doesn't replace var name
Expand Down Expand Up @@ -54,6 +55,8 @@ <h1>Define</h1>

import { defined } from 'dep'
text('.define-in-dep', JSON.stringify(defined))

text('.key-includes-dash', 'KEY-INCLUDES-DASH')
</script>

<style>
Expand Down
3 changes: 2 additions & 1 deletion playground/define/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ module.exports = {
$DOLLAR: 456,
ÖUNICODE_LETTERɵ: 789,
__VAR_NAME__: false,
__STRINGIFIED_OBJ__: JSON.stringify({ foo: true })
__STRINGIFIED_OBJ__: JSON.stringify({ foo: true }),
'KEY-INCLUDES-DASH': true
}
}