Skip to content

Commit a95aa0b

Browse files
sapphi-redunderfin
andcommitted
feat: add plugin-react-oxc
Co-authored-by: underfin <[email protected]>
1 parent 6085bbe commit a95aa0b

File tree

12 files changed

+538
-1
lines changed

12 files changed

+538
-1
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Changelog
2+
3+
## Unreleased
4+
5+
- Create Oxc plugin

packages/plugin-react-oxc/LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# @vitejs/plugin-react-oxc [![npm](https://img.shields.io/npm/v/@vitejs/plugin-react-oxc.svg)](https://npmjs.com/package/@vitejs/plugin-react-oxc)
2+
3+
```js
4+
// vite.config.js
5+
import { defineConfig } from 'vite'
6+
import react from '@vitejs/plugin-react-oxc'
7+
8+
export default defineConfig({
9+
plugins: [react()],
10+
})
11+
```
12+
13+
## Caveats
14+
15+
- `jsx runtime` is always `automatic`
16+
- this plugin only works with `rolldown-vite`
17+
18+
## Options
19+
20+
### include/exclude
21+
22+
Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to add fast refresh to `.mdx` files:
23+
24+
```js
25+
import { defineConfig } from 'vite'
26+
import react from '@vitejs/plugin-react'
27+
import mdx from '@mdx-js/rollup'
28+
29+
export default defineConfig({
30+
plugins: [
31+
{ enforce: 'pre', ...mdx() },
32+
react({ include: /\.(mdx|js|jsx|ts|tsx)$/ }),
33+
],
34+
})
35+
```
36+
37+
> `node_modules` are never processed by this plugin (but esbuild will)
38+
39+
### jsxImportSource
40+
41+
Control where the JSX factory is imported from. Default to `'react'`
42+
43+
```js
44+
react({ jsxImportSource: '@emotion/react' })
45+
```
46+
47+
## Middleware mode
48+
49+
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:
50+
51+
```js
52+
app.get('/', async (req, res, next) => {
53+
try {
54+
let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8')
55+
56+
// Transform HTML using Vite plugins.
57+
html = await viteServer.transformIndexHtml(req.url, html)
58+
59+
res.send(html)
60+
} catch (e) {
61+
return next(e)
62+
}
63+
})
64+
```
65+
66+
Otherwise, you'll probably get this error:
67+
68+
```
69+
Uncaught Error: @vitejs/plugin-react-oxc can't detect preamble. Something is wrong.
70+
```
71+
72+
## Consistent components exports
73+
74+
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).
75+
76+
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.
77+
78+
You can catch mistakes and get more detailed warning with this [eslint rule](https://github.com/ArnaudBarre/eslint-plugin-react-refresh).
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { defineBuildConfig } from 'unbuild'
2+
3+
export default defineBuildConfig({
4+
entries: ['src/index'],
5+
externals: ['vite'],
6+
clean: true,
7+
declaration: true,
8+
rollup: {
9+
inlineDependencies: true,
10+
},
11+
})
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
{
2+
"name": "@vitejs/plugin-react-oxc",
3+
"version": "0.1.0",
4+
"license": "MIT",
5+
"author": "Evan You",
6+
"contributors": [
7+
"Alec Larson",
8+
"Arnaud Barré"
9+
],
10+
"files": [
11+
"dist"
12+
],
13+
"type": "module",
14+
"exports": "./dist/index.mjs",
15+
"scripts": {
16+
"dev": "unbuild --stub",
17+
"build": "unbuild && tsx scripts/copyRefreshUtils.ts",
18+
"prepublishOnly": "npm run build"
19+
},
20+
"engines": {
21+
"node": ">=20.0.0"
22+
},
23+
"repository": {
24+
"type": "git",
25+
"url": "git+https://github.com/vitejs/vite-plugin-react.git",
26+
"directory": "packages/plugin-react-oxc"
27+
},
28+
"bugs": {
29+
"url": "https://github.com/vitejs/vite-plugin-react/issues"
30+
},
31+
"homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#readme",
32+
"dependencies": {
33+
"react-refresh": "^0.14.2"
34+
},
35+
"peerDependencies": {
36+
"vite": "^6.3.0"
37+
},
38+
"devDependencies": {
39+
"unbuild": "^3.5.0"
40+
}
41+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { copyFileSync } from 'node:fs'
2+
3+
copyFileSync('src/refreshUtils.js', 'dist/refreshUtils.js')
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import fs from 'node:fs'
2+
import path from 'node:path'
3+
import { createRequire } from 'node:module'
4+
5+
export const runtimePublicPath = '/@react-refresh'
6+
7+
const _require = createRequire(import.meta.url)
8+
const reactRefreshDir = path.dirname(
9+
_require.resolve('react-refresh/package.json'),
10+
)
11+
const runtimeFilePath = path.join(
12+
reactRefreshDir,
13+
'cjs/react-refresh-runtime.development.js',
14+
)
15+
16+
export const runtimeCode = `
17+
const exports = {}
18+
${fs.readFileSync(runtimeFilePath, 'utf-8')}
19+
${fs.readFileSync(_require.resolve('./refreshUtils.js'), 'utf-8')}
20+
export default exports
21+
`
22+
23+
export const preambleCode = `
24+
import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}"
25+
RefreshRuntime.injectIntoGlobalHook(window)
26+
window.$RefreshReg$ = () => {}
27+
window.$RefreshSig$ = () => (type) => type
28+
window.__vite_plugin_react_preamble_installed__ = true
29+
`
30+
31+
const sharedHeader = `
32+
import RefreshRuntime from "${runtimePublicPath}";
33+
34+
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
35+
`.replace(/\n+/g, '')
36+
const functionHeader = `
37+
let prevRefreshReg;
38+
let prevRefreshSig;
39+
40+
if (import.meta.hot && !inWebWorker) {
41+
if (!window.__vite_plugin_react_preamble_installed__) {
42+
throw new Error(
43+
"@vitejs/plugin-react-oxc can't detect preamble. Something is wrong. " +
44+
"See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201"
45+
);
46+
}
47+
48+
prevRefreshReg = window.$RefreshReg$;
49+
prevRefreshSig = window.$RefreshSig$;
50+
window.$RefreshReg$ = (type, id) => {
51+
RefreshRuntime.register(type, __SOURCE__ + " " + id)
52+
};
53+
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
54+
}`.replace(/\n+/g, '')
55+
56+
const functionFooter = `
57+
if (import.meta.hot && !inWebWorker) {
58+
window.$RefreshReg$ = prevRefreshReg;
59+
window.$RefreshSig$ = prevRefreshSig;
60+
}`
61+
const sharedFooter = (id: string) => `
62+
if (import.meta.hot && !inWebWorker) {
63+
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
64+
RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(
65+
id,
66+
)}, currentExports);
67+
import.meta.hot.accept((nextExports) => {
68+
if (!nextExports) return;
69+
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(
70+
id,
71+
)}, currentExports, nextExports);
72+
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
73+
});
74+
});
75+
}`
76+
77+
export function addRefreshWrapper(code: string, id: string): string {
78+
return (
79+
sharedHeader +
80+
functionHeader.replace('__SOURCE__', JSON.stringify(id)) +
81+
code +
82+
functionFooter +
83+
sharedFooter(id)
84+
)
85+
}
86+
87+
export function addClassComponentRefreshWrapper(
88+
code: string,
89+
id: string,
90+
): string {
91+
return sharedHeader + code + sharedFooter(id)
92+
}

0 commit comments

Comments
 (0)