Skip to content
Merged
Show file tree
Hide file tree
Changes from 21 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
43 changes: 33 additions & 10 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 | null | undefined | string } {
const hasRefresh = refreshContentRE.test(code)
const onlyReactComp = !hasRefresh && reactCompRE.test(code)
if (!hasRefresh && !onlyReactComp) return { code, map }
const normalizedMap = map === avoidSourceMapOption ? null : map

if (!hasRefresh && !onlyReactComp) return { code, map: normalizedMap }

const avoidSourceMap = map === avoidSourceMapOption
const newMap =
typeof normalizedMap === 'string'
? (JSON.parse(normalizedMap) as M)
: normalizedMap

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,22 +53,31 @@ if (import.meta.hot && !inWebWorker) {
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
}

${newCode}
`,
avoidSourceMap,
)

newCode = `${refreshHead}${newCode}

if (import.meta.hot && !inWebWorker) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
}
`
if (newMap) {
newMap.mappings = ';'.repeat(17) + newMap.mappings
newMap.mappings = ';'.repeat(16) + newMap.mappings
}
}

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,
},
})
50 changes: 50 additions & 0 deletions packages/plugin-react-oxc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"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",
"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