Skip to content

Commit

Permalink
feat: add option to exclude global define and env replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
ygj6 committed Mar 31, 2022
1 parent 67ac7d8 commit 295b887
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 33 deletions.
4 changes: 4 additions & 0 deletions packages/playground/define/__tests__/define.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,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`
5 changes: 5 additions & 0 deletions packages/playground/define/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@ <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', typeof __EXP__) // typeof __EXP_ would be `boolean` instead of `string`
text('.string', __STRING__)
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"
}
}
10 changes: 10 additions & 0 deletions packages/playground/define/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
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__: 'false',
__STRING__: '"hello"',
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

0 comments on commit 295b887

Please sign in to comment.