Skip to content

feat: add filter #470

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

Merged
merged 6 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 8 additions & 0 deletions packages/common/filter-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function exactRegex(input: string): RegExp {
return new RegExp(`^${escapeRegex(input)}$`)
}

const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g
function escapeRegex(str: string): string {
return str.replace(escapeRegexRE, '\\$&')
}
1 change: 1 addition & 0 deletions packages/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './filter-utils'
export * from './refresh-utils'
export * from './warning'
10 changes: 1 addition & 9 deletions packages/plugin-react-oxc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { BuildOptions, Plugin, PluginOption } from 'vite'
import {
addRefreshWrapper,
avoidSourceMapOption,
exactRegex,
getPreambleCode,
runtimePublicPath,
silenceUseClientWarning,
Expand Down Expand Up @@ -149,12 +150,3 @@ export default function viteReact(opts: Options = {}): PluginOption[] {

return [viteConfig, viteRefreshRuntime, viteRefreshWrapper]
}

function exactRegex(input: string): RegExp {
return new RegExp(`^${escapeRegex(input)}$`)
}

const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g
function escapeRegex(str: string): string {
return str.replace(escapeRegexRE, '\\$&')
}
26 changes: 18 additions & 8 deletions packages/plugin-react-swc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import type { PluginOption } from 'vite'
import {
addRefreshWrapper,
exactRegex,
getPreambleCode,
runtimePublicPath,
silenceUseClientWarning,
Expand Down Expand Up @@ -96,14 +97,23 @@ const react = (_options?: Options): PluginOption[] => {
name: 'vite:react-swc:resolve-runtime',
apply: 'serve',
enforce: 'pre', // Run before Vite default resolve to avoid syscalls
resolveId: (id) => (id === runtimePublicPath ? id : undefined),
load: (id) =>
id === runtimePublicPath
? readFileSync(join(_dirname, 'refresh-runtime.js'), 'utf-8').replace(
/__README_URL__/g,
'https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc',
)
: undefined,
resolveId: {
filter: { id: exactRegex(runtimePublicPath) },
handler: (id) => (id === runtimePublicPath ? id : undefined),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still need to keep the if statements to keep the compat for Vite older than v6.3.

},
load: {
filter: { id: exactRegex(runtimePublicPath) },
handler: (id) =>
id === runtimePublicPath
? readFileSync(
join(_dirname, 'refresh-runtime.js'),
'utf-8',
).replace(
/__README_URL__/g,
'https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc',
)
: undefined,
},
},
{
name: 'vite:react-swc',
Expand Down
243 changes: 134 additions & 109 deletions packages/plugin-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as vite from 'vite'
import type { Plugin, PluginOption, ResolvedConfig } from 'vite'
import {
addRefreshWrapper,
exactRegex,
getPreambleCode,
preambleCode,
runtimePublicPath,
Expand Down Expand Up @@ -181,114 +182,120 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
// we only create static option in this case and re-create them
// each time otherwise
staticBabelOptions = createBabelOptions(opts.babel)

if (
canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) &&
skipFastRefresh &&
isProduction
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isProduction implies skipFastRefresh for now so we can skip the second check but it doesn't hurt so up to you

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I think this is needed. For example, when config.command === 'build' && !isProduction is true (NODE_ENV=development vite build), this if block should not be executed. Otherwise @babel/plugin-transform-react-jsx-self / @babel/plugin-transform-react-jsx-source won't run.

) {
delete viteBabel.transform
}
}
},
async transform(code, id, options) {
if (id.includes('/node_modules/')) return

const [filepath] = id.split('?')
if (!filter(filepath)) return

const ssr = options?.ssr === true
const babelOptions = (() => {
if (staticBabelOptions) return staticBabelOptions
const newBabelOptions = createBabelOptions(
typeof opts.babel === 'function'
? opts.babel(id, { ssr })
: opts.babel,
)
runPluginOverrides?.(newBabelOptions, { id, ssr })
return newBabelOptions
})()
const plugins = [...babelOptions.plugins]

const isJSX = filepath.endsWith('x')
const useFastRefresh =
!skipFastRefresh &&
!ssr &&
(isJSX ||
(opts.jsxRuntime === 'classic'
? importReactRE.test(code)
: code.includes(jsxImportDevRuntime) ||
code.includes(jsxImportRuntime)))
if (useFastRefresh) {
plugins.push([
await loadPlugin('react-refresh/babel'),
{ skipEnvCheck: true },
])
}

if (opts.jsxRuntime === 'classic' && isJSX) {
if (!isProduction) {
// These development plugins are only needed for the classic runtime.
plugins.push(
await loadPlugin('@babel/plugin-transform-react-jsx-self'),
await loadPlugin('@babel/plugin-transform-react-jsx-source'),
transform: {
filter: { id: { exclude: /\/node_modules\// } },
async handler(code, id, options) {
if (id.includes('/node_modules/')) return

const [filepath] = id.split('?')
if (!filter(filepath)) return

const ssr = options?.ssr === true
const babelOptions = (() => {
if (staticBabelOptions) return staticBabelOptions
const newBabelOptions = createBabelOptions(
typeof opts.babel === 'function'
? opts.babel(id, { ssr })
: opts.babel,
)
runPluginOverrides?.(newBabelOptions, { id, ssr })
return newBabelOptions
})()
const plugins = [...babelOptions.plugins]

const isJSX = filepath.endsWith('x')
const useFastRefresh =
!skipFastRefresh &&
!ssr &&
(isJSX ||
(opts.jsxRuntime === 'classic'
? importReactRE.test(code)
: code.includes(jsxImportDevRuntime) ||
code.includes(jsxImportRuntime)))
if (useFastRefresh) {
plugins.push([
await loadPlugin('react-refresh/babel'),
{ skipEnvCheck: true },
])
}
}

// Avoid parsing if no special transformation is needed
if (
!plugins.length &&
!babelOptions.presets.length &&
!babelOptions.configFile &&
!babelOptions.babelrc
) {
return
}
if (opts.jsxRuntime === 'classic' && isJSX) {
if (!isProduction) {
// These development plugins are only needed for the classic runtime.
plugins.push(
await loadPlugin('@babel/plugin-transform-react-jsx-self'),
await loadPlugin('@babel/plugin-transform-react-jsx-source'),
)
}
}

const parserPlugins = [...babelOptions.parserOpts.plugins]
// Avoid parsing if no special transformation is needed
if (canSkipBabel(plugins, babelOptions)) {
return
}

if (!filepath.endsWith('.ts')) {
parserPlugins.push('jsx')
}
const parserPlugins = [...babelOptions.parserOpts.plugins]

if (tsRE.test(filepath)) {
parserPlugins.push('typescript')
}
if (!filepath.endsWith('.ts')) {
parserPlugins.push('jsx')
}

const babel = await loadBabel()
const result = await babel.transformAsync(code, {
...babelOptions,
root: projectRoot,
filename: id,
sourceFileName: filepath,
// Required for esbuild.jsxDev to provide correct line numbers
// This creates issues the react compiler because the re-order is too important
// People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
retainLines:
getReactCompilerPlugin(plugins) != null
? false
: !isProduction && isJSX && opts.jsxRuntime !== 'classic',
parserOpts: {
...babelOptions.parserOpts,
sourceType: 'module',
allowAwaitOutsideFunction: true,
plugins: parserPlugins,
},
generatorOpts: {
...babelOptions.generatorOpts,
// import attributes parsing available without plugin since 7.26
importAttributesKeyword: 'with',
decoratorsBeforeExport: true,
},
plugins,
sourceMaps: true,
})

if (result) {
if (!useFastRefresh) {
return { code: result.code!, map: result.map }
if (tsRE.test(filepath)) {
parserPlugins.push('typescript')
}
return addRefreshWrapper(
result.code!,
result.map!,
'@vitejs/plugin-react',
id,
opts.reactRefreshHost,
)
}

const babel = await loadBabel()
const result = await babel.transformAsync(code, {
...babelOptions,
root: projectRoot,
filename: id,
sourceFileName: filepath,
// Required for esbuild.jsxDev to provide correct line numbers
// This creates issues the react compiler because the re-order is too important
// People should use @babel/plugin-transform-react-jsx-development to get back good line numbers
retainLines:
getReactCompilerPlugin(plugins) != null
? false
: !isProduction && isJSX && opts.jsxRuntime !== 'classic',
parserOpts: {
...babelOptions.parserOpts,
sourceType: 'module',
allowAwaitOutsideFunction: true,
plugins: parserPlugins,
},
generatorOpts: {
...babelOptions.generatorOpts,
// import attributes parsing available without plugin since 7.26
importAttributesKeyword: 'with',
decoratorsBeforeExport: true,
},
plugins,
sourceMaps: true,
})

if (result) {
if (!useFastRefresh) {
return { code: result.code!, map: result.map }
}
return addRefreshWrapper(
result.code!,
result.map!,
'@vitejs/plugin-react',
id,
opts.reactRefreshHost,
)
}
},
},
}

Expand Down Expand Up @@ -319,18 +326,24 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
dedupe: ['react', 'react-dom'],
},
}),
resolveId(id) {
if (id === runtimePublicPath) {
return id
}
resolveId: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return id
}
},
},
load(id) {
if (id === runtimePublicPath) {
return readFileSync(refreshRuntimePath, 'utf-8').replace(
/__README_URL__/g,
'https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react',
)
}
load: {
filter: { id: exactRegex(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) {
return readFileSync(refreshRuntimePath, 'utf-8').replace(
/__README_URL__/g,
'https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react',
)
}
},
},
transformIndexHtml(_, config) {
if (!skipFastRefresh)
Expand All @@ -349,6 +362,18 @@ export default function viteReact(opts: Options = {}): PluginOption[] {

viteReact.preambleCode = preambleCode

function canSkipBabel(
plugins: ReactBabelOptions['plugins'],
babelOptions: ReactBabelOptions,
) {
return !(
plugins.length ||
babelOptions.presets.length ||
babelOptions.configFile ||
babelOptions.babelrc
)
}

const loadedPlugin = new Map<string, any>()
function loadPlugin(path: string): any {
const cached = loadedPlugin.get(path)
Expand Down
Loading