Skip to content
Merged
Show file tree
Hide file tree
Changes from 18 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
2 changes: 2 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ body:
[plugin-react](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react)
- label: |
[plugin-react-swc](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc)
- label: |
[plugin-react-oxc](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-oxc)
- type: textarea
id: bug-description
attributes:
Expand Down
2 changes: 2 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ body:
[plugin-react](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react)
- label: |
[plugin-react-swc](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-swc)
- label: |
[plugin-react-oxc](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react-oxc)
- type: textarea
id: feature-description
attributes:
Expand Down
41 changes: 32 additions & 9 deletions packages/common/refresh-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,30 @@ window.$RefreshSig$ = () => (type) => type;`
export const getPreambleCode = (base: string): string =>
preambleCode.replace('__BASE__', base)

export function addRefreshWrapper<M extends { mappings: string } | undefined>(
export const avoidSourceMapOption = Symbol()

export function addRefreshWrapper<M extends { mappings: string }>(
code: string,
map: M | string,
map: M | string | undefined | typeof avoidSourceMapOption,
pluginName: string,
id: string,
): { code: string; map: M | string } {
): { code: string; map: M | undefined | string } {
const hasRefresh = refreshContentRE.test(code)
const onlyReactComp = !hasRefresh && reactCompRE.test(code)
if (!hasRefresh && !onlyReactComp) return { code, map }
const newMap =
map === avoidSourceMapOption
Copy link
Member

Choose a reason for hiding this comment

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

Did you try generated an empty source map that will then only be ';'.repeat(17) + newMap.mappings?
Not a big deal but cleaner when you inspect the pipeline changes

Copy link
Member Author

Choose a reason for hiding this comment

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

It's because newMap doesn't exist here.
https://github.com/vitejs/vite-plugin-react/pull/439/files#diff-57c3aa7ebcc7d479870d1da730fee916a15a41215f2a6af821383235f62f3b59R114-R129
We can generate it by new MagicString(code).generateMap({ hires: 'boundary' }), but I guess that has a bigger overhead.

Copy link
Member

Choose a reason for hiding this comment

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

Does rollup allows to get the current sourceMap of the transform pipeline?
So we can edit it instead of generating a new one and having Vite merge them after

Copy link
Member Author

Choose a reason for hiding this comment

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

It has a way to get the current combined source map (this.getCombinedSourcemap). But there isn't a way to tell rollup that the returned sourcemap is a combined one.

Copy link
Member

Choose a reason for hiding this comment

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

I did some experiment but using an empty sourceMappings where only ; is apprend breaks the concatenation somewhere because the output doesn't contain any source map (without logs)

So I tried this:

        const { code: newCode, map } = addRefreshWrapper(
          code,
          {
            version: 3,
            file: undefined,
            sources: [''],
            sourcesContent: undefined,
            names: [],
            mappings: 'AAAA;'.repeat(code.split('\n').length - 1),
          },
          '@vitejs/plugin-react-oxc',
          id,
        )
        return { code: newCode, map }

Inspired by what magic-string does as a default and once again was surprised out slow unpredictable JS perf is.

This test also made me find that the ';'.repeat should be 16 and not 17 because there are 17 lines but 16 line breaks.

With the change I have this kind of output.

For Babel I found that's it's a bit broken.

For SWC it map a bit more (onClick) but fails the children is off

I'm still ok for going the full first line inline way, it feels hacky for me but probably only people like me look at generated code, the same way normal people never look at the URL 😅

Copy link
Member Author

@sapphi-red sapphi-red Apr 8, 2025

Choose a reason for hiding this comment

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

'AAAA;'.repeat(code.split('\n').length - 1),

I think this works similarly to hires: false and probably that's the reason the sourcemap is a bit broken when combined with babel.

I prefer to go with the current way for now.

Copy link
Member

Choose a reason for hiding this comment

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

Nope the soucemap is perfectly valid, it just says the line didn't change which is true. When combined it works well with the OXC sourcemap
On the babel plugin the sourcemap is not working great but that's nothing to do with 'AAAA;'.repeat(code.split('\n').length - 1) which I added only on the OXC plugin

Copy link
Member Author

Choose a reason for hiding this comment

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

Nope the soucemap is perfectly valid, it just says the line didn't change which is true.

'AAAA;'.repeat(code.split('\n').length - 1) only maps the first character of each lines (which is the same behavior with hires: false). If I remember correctly, the position of console.log will be at the first character of the line rather than the position next to console.log. This is not that important as we have multiple places doing similar to it (it's better if we can avoid them though). But in addition to that, it causes troubles when combined with other sourcemaps.
https://x.com/bluwyoo/status/1674036158714769408 (I didn't find any examples, only found this post 😅)

Copy link
Member Author

Choose a reason for hiding this comment

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

What we want is a range mapping (a proposal exists: https://github.com/tc39/ecma426/blob/main/proposals/range-mappings.md), but currently sourcemaps only supports character-by-character mapping.

Copy link
Member

Choose a reason for hiding this comment

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

Ok thanks I see and I understand now why people wants a new source map spec 😅
That's sad that such a common usecase is not easy to do 😢

? undefined
: typeof map === 'string'
? (JSON.parse(map) as M)
: map
if (!hasRefresh && !onlyReactComp) return { code, map: newMap }

const avoidSourceMap = map === avoidSourceMapOption

const newMap = typeof map === 'string' ? (JSON.parse(map) as M) : map
let newCode = code
if (hasRefresh) {
newCode = `let prevRefreshReg;
const refreshHead = removeLineBreaksIfNeeded(
`let prevRefreshReg;
let prevRefreshSig;

if (import.meta.hot && !inWebWorker) {
Expand All @@ -43,7 +53,11 @@ if (import.meta.hot && !inWebWorker) {
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
}

${newCode}
`,
avoidSourceMap,
)

newCode = `${refreshHead}${newCode}

if (import.meta.hot && !inWebWorker) {
window.$RefreshReg$ = prevRefreshReg;
Expand All @@ -55,10 +69,15 @@ if (import.meta.hot && !inWebWorker) {
}
}

newCode = `import * as RefreshRuntime from "${runtimePublicPath}";
const sharedHead = removeLineBreaksIfNeeded(
`import * as RefreshRuntime from "${runtimePublicPath}";
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;

${newCode}
`,
avoidSourceMap,
)

newCode = `${sharedHead}${newCode}

if (import.meta.hot && !inWebWorker) {
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
Expand All @@ -81,3 +100,7 @@ if (import.meta.hot && !inWebWorker) {

return { code: newCode, map: newMap }
}

function removeLineBreaksIfNeeded(code: string, enabled: boolean): string {
return enabled ? code.replace(/\n/g, '') : code
}
5 changes: 5 additions & 0 deletions packages/plugin-react-oxc/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## Unreleased

- Create Oxc plugin
21 changes: 21 additions & 0 deletions packages/plugin-react-oxc/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
84 changes: 84 additions & 0 deletions packages/plugin-react-oxc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# @vitejs/plugin-react-oxc [![npm](https://img.shields.io/npm/v/@vitejs/plugin-react-oxc.svg)](https://npmjs.com/package/@vitejs/plugin-react-oxc)

The future default Vite plugin for React projects.

- enable [Fast Refresh](https://www.npmjs.com/package/react-refresh) in development
- use the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html)
- small installation size

```js
// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-oxc'

export default defineConfig({
plugins: [react()],
})
```

## Caveats

- `jsx runtime` is always `automatic`
- this plugin only works with [`rolldown-vite`](https://vitejs.dev/guide/rolldown)

## Options

### include/exclude

Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to add fast refresh to `.mdx` files:

```js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import mdx from '@mdx-js/rollup'

export default defineConfig({
plugins: [
{ enforce: 'pre', ...mdx() },
react({ include: /\.(mdx|js|jsx|ts|tsx)$/ }),
],
})
```

> `node_modules` are never processed by this plugin (but Oxc will)

### jsxImportSource

Control where the JSX factory is imported from. Default to `'react'`

```js
react({ jsxImportSource: '@emotion/react' })
```

## Middleware mode

In [middleware mode](https://vite.dev/config/server-options.html#server-middlewaremode), you should make sure your entry `index.html` file is transformed by Vite. Here's an example for an Express server:

```js
app.get('/', async (req, res, next) => {
try {
let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8')

// Transform HTML using Vite plugins.
html = await viteServer.transformIndexHtml(req.url, html)

res.send(html)
} catch (e) {
return next(e)
}
})
```

Otherwise, you'll probably get this error:

```
Uncaught Error: @vitejs/plugin-react-oxc can't detect preamble. Something is wrong.
```

## Consistent components exports

For React refresh to work correctly, your file should only export React components. You can find a good explanation in the [Gatsby docs](https://www.gatsbyjs.com/docs/reference/local-development/fast-refresh/#how-it-works).

If an incompatible change in exports is found, the module will be invalidated and HMR will propagate. To make it easier to export simple constants alongside your component, the module is only invalidated when their value changes.

You can catch mistakes and get more detailed warning with this [eslint rule](https://github.com/ArnaudBarre/eslint-plugin-react-refresh).
11 changes: 11 additions & 0 deletions packages/plugin-react-oxc/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
entries: ['src/index'],
externals: ['vite'],
clean: true,
declaration: true,
rollup: {
inlineDependencies: true,
},
})
53 changes: 53 additions & 0 deletions packages/plugin-react-oxc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "@vitejs/plugin-react-oxc",
"version": "0.1.0",
"license": "MIT",
"author": "Evan You",
"contributors": [
"Alec Larson",
"Arnaud Barré"
],
"description": "The future default Vite plugin for React projects",
"keywords": [
"vite",
"vite-plugin",
"react",
"oxc",
"react-refresh",
"fast refresh"
],
"files": [
"dist"
],
"type": "module",
"types": "./dist/index.d.mts",
"exports": "./dist/index.mjs",
"scripts": {
"dev": "unbuild --stub",
"build": "unbuild && tsx scripts/copyRefreshRuntime.ts",
"prepublishOnly": "npm run build"
},
"engines": {
"node": ">=20.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vitejs/vite-plugin-react.git",
"directory": "packages/plugin-react-oxc"
},
"bugs": {
"url": "https://github.com/vitejs/vite-plugin-react/issues"
},
"homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#readme",
"dependencies": {
"react-refresh": "^0.14.2"
},
"peerDependencies": {
"vite": "^6.3.0"
},
"devDependencies": {
"@vitejs/react-common": "workspace:*",
"unbuild": "^3.5.0",
"vite": "catalog:rolldown-vite"
}
}
6 changes: 6 additions & 0 deletions packages/plugin-react-oxc/scripts/copyRefreshRuntime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { copyFileSync } from 'node:fs'

copyFileSync(
'node_modules/@vitejs/react-common/refresh-runtime.js',
'dist/refresh-runtime.js',
)
Loading
Loading