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: add option to exclude global define and env replacement #5577

Closed
wants to merge 2 commits 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/playground/define/__tests__/define.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
test('string', async () => {
const defines = require('../vite.config.js').define

expect(await page.textContent('.exp')).toBe(String(eval(defines.__EXP__)))
expect(await page.textContent('.exp')).toBe(
String(typeof eval(defines.__EXP__))
)
expect(await page.textContent('.string')).toBe(JSON.parse(defines.__STRING__))
expect(await page.textContent('.number')).toBe(String(defines.__NUMBER__))
expect(await page.textContent('.boolean')).toBe(String(defines.__BOOLEAN__))
Expand All @@ -24,3 +26,7 @@ test('string', async () => {
expect(await page.textContent('.exp-define')).toBe('__EXP__')
expect(await page.textContent('.import-json')).toBe('__EXP__')
})

test('exclude replacement', async () => {
expect(await page.textContent('.origin-text')).toMatch('process.env.NODE_ENV')
})
1 change: 1 addition & 0 deletions packages/playground/define/env.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`process.env.NODE_ENV`
7 changes: 6 additions & 1 deletion packages/playground/define/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,15 @@ <h1>Define</h1>
<p>spread array: <code class="spread-array"></code></p>
<p>define variable in html: <code class="exp-define">__EXP__</code></p>
<p>import json: <code class="import-json"></code></p>
<p id="md-to-vue" class="origin-text">{{msg}}</p>

<script type="module">
import { createApp } from 'vue'
import EnvComponent from './env.md'
createApp(EnvComponent).mount('#md-to-vue')

const __VAR_NAME__ = true // ensure define doesn't replace var name
text('.exp', __EXP__)
text('.exp', typeof __EXP__) // typeof __EXP_ would be `boolean` instead of `string`
text('.string', __STRING__)
text('.number', __NUMBER__)
text('.boolean', __BOOLEAN__)
Expand Down
7 changes: 7 additions & 0 deletions packages/playground/define/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,12 @@
"build": "vite build",
"debug": "node --inspect-brk ../../vite/bin/vite",
"preview": "vite preview"
},
"devDependencies": {
"@vitejs/plugin-vue": "workspace:*",
"vite-plugin-md": "^0.11.4"
},
"dependencies": {
"vue": "^3.2.16"
}
}
12 changes: 11 additions & 1 deletion packages/playground/define/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
const Vue = require('@vitejs/plugin-vue')
const Markdown = require('vite-plugin-md').default

module.exports = {
replacementExclude: ['**.md'],
plugins: [
Vue({
include: [/\.vue$/, /\.md$/]
}),
Markdown()
],
define: {
__EXP__: '1 + 1',
__EXP__: 'false',
__STRING__: '"hello"',
__NUMBER__: 123,
__BOOLEAN__: true,
Expand Down
25 changes: 23 additions & 2 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ export interface UserConfig {
* Entries will be defined on `window` during dev and replaced during build.
*/
define?: Record<string, any>
/**
* Specify additional picomatch patterns to exclude global defines and env replacement.
*/
replacementExclude?: string | RegExp | (string | RegExp)[]
/**
* Array of vite plugins to use.
*/
Expand Down Expand Up @@ -237,7 +241,13 @@ export interface InlineConfig extends UserConfig {
export type ResolvedConfig = Readonly<
Omit<
UserConfig,
'plugins' | 'alias' | 'dedupe' | 'assetsInclude' | 'optimizeDeps' | 'worker'
| 'plugins'
| 'alias'
| 'dedupe'
| 'assetsInclude'
| 'replacementExclude'
| 'optimizeDeps'
| 'worker'
> & {
configFile: string | undefined
configFileDependencies: string[]
Expand All @@ -259,6 +269,7 @@ export type ResolvedConfig = Readonly<
build: ResolvedBuildOptions
preview: ResolvedPreviewOptions
assetsInclude: (file: string) => boolean
replacementExclude: (file: string) => boolean
logger: Logger
createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn
optimizeDeps: Omit<DepOptimizationOptions, 'keepNames'>
Expand Down Expand Up @@ -413,6 +424,10 @@ export async function resolveConfig(
? createFilter(config.assetsInclude)
: () => false

const definesFilter = config.replacementExclude
? createFilter(config.replacementExclude)
: () => false

// create an internal resolver to be used in special scenarios, e.g.
// optimizer & handling css @imports
const createResolver: ResolvedConfig['createResolver'] = (options) => {
Expand Down Expand Up @@ -493,6 +508,9 @@ export async function resolveConfig(
assetsInclude(file: string) {
return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file)
},
replacementExclude(file: string) {
return definesFilter(file)
},
logger,
packageCache: new Map(),
createResolver,
Expand Down Expand Up @@ -740,7 +758,10 @@ function mergeConfigRecursively(
if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
merged[key] = mergeAlias(existing, value)
continue
} else if (key === 'assetsInclude' && rootPath === '') {
} else if (
(key === 'assetsInclude' || key === 'replacementExclude') &&
rootPath === ''
) {
merged[key] = [].concat(existing, value)
continue
} else if (key === 'noExternal' && existing === true) {
Expand Down
6 changes: 5 additions & 1 deletion packages/vite/src/node/plugins/clientInjections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ export function clientInjectionsPlugin(config: ResolvedConfig): Plugin {
.replace(`__HMR_PORT__`, JSON.stringify(port))
.replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout))
.replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay))
} else if (!options?.ssr && code.includes('process.env.NODE_ENV')) {
} else if (
!config.replacementExclude(id) &&
!options?.ssr &&
code.includes('process.env.NODE_ENV')
) {
// replace process.env.NODE_ENV instead of defining a global
// for it to avoid shimming a `process` object during dev,
// avoiding inconsistencies between dev and build
Expand Down
5 changes: 3 additions & 2 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,12 @@ export function definePlugin(config: ResolvedConfig): Plugin {
}

if (
// exclude html, css and static assets for performance
// exclude html, specified file, css and static assets for performance
isHTMLRequest(id) ||
isCSSRequest(id) ||
isNonJsRequest(id) ||
config.assetsInclude(id)
config.assetsInclude(id) ||
config.replacementExclude(id)
) {
return
}
Expand Down
Loading