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 2 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: 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
273 changes: 164 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 @@ -102,7 +103,10 @@ const defaultIncludeRE = /\.[tj]sx?$/
const tsRE = /\.tsx?$/

export default function viteReact(opts: Options = {}): PluginOption[] {
const filter = createFilter(opts.include ?? defaultIncludeRE, opts.exclude)
const include = opts.include ?? defaultIncludeRE
const exclude = opts.exclude
const filter = createFilter(include, exclude)

const jsxImportSource = opts.jsxImportSource ?? 'react'
const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`
const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`
Expand Down Expand Up @@ -181,114 +185,128 @@ 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: {
include: ensureArray(include).map(matchWithQuery),
exclude: [
...(exclude ? ensureArray(exclude).map(matchWithQuery) : []),
/\/node_modules\//,
],
Copy link
Member

Choose a reason for hiding this comment

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

This filter conversion and the two utils feels a bit tricky IMO.
Could this be upstream into the Vite createFilter function so that it can be reused by other plugins?

Copy link
Member Author

Choose a reason for hiding this comment

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

If we add a util function to Vite, we need to bump the required peer dep in this plugin (and the other plugins that wants to use that) which is a breaking change. I think if we do that we probably should add it to a separate package.

I'll consider if we can have @rolldown/pluginutils (since I sent a PR to @rollup/pluginutils that adds some utils functions and it's taking some time to be merged).

Copy link
Member

Choose a reason for hiding this comment

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

This could be added and then we could do import * as Vite from 'vite' and check for the export name existence so that people using the latest version have the speedup (which is expecting for people running rolldown vite)

Copy link
Member Author

Choose a reason for hiding this comment

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

I've updated the code to use @rolldown/pluginutils. ensureArray is still there because we need to combine with /\/node_modules\//, but I think it is now simple enough.

},
},
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 (tsRE.test(filepath)) {
parserPlugins.push('typescript')
}

if (result) {
if (!useFastRefresh) {
return { code: result.code!, map: result.map }
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,
)
}
return addRefreshWrapper(
result.code!,
result.map!,
'@vitejs/plugin-react',
id,
opts.reactRefreshHost,
)
}
},
},
}

Expand Down Expand Up @@ -319,18 +337,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 +373,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 Expand Up @@ -408,3 +444,22 @@ function getReactCompilerRuntimeModule(
}
return moduleName
}

function ensureArray<T>(value: T | T[]): T[] {
return Array.isArray(value) ? value : [value]
}

function matchWithQuery(input: string | RegExp) {
if (typeof input === 'string') {
return `${input}{?*,}`
}
return addQueryToRegex(input)
}

function addQueryToRegex(input: RegExp) {
return new RegExp(
// replace `$` with `(?:\?.*)?$` (ignore `\$`)
input.source.replace(/(?<!\\)\$/g, '(?:\\?.*)?$'),
input.flags,
)
}
Loading