Skip to content

fix!: don't auto import React with classic runtime #150

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 2 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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/plugin-react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ Control where the JSX factory is imported from. Default to `'react'`
react({ jsxImportSource: '@emotion/react' })
```

## jsxRuntime

By default, the plugin uses the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). However, if you encounter any issues, you may opt out using the `jsxRuntime` option.

```js
react({ jsxRuntime: 'classic' })
```

### babel

The `babel` option lets you add plugins, presets, and [other configuration](https://babeljs.io/docs/en/options) to the Babel transformation performed on each included file.
Expand Down
1 change: 0 additions & 1 deletion packages/plugin-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
"@babel/core": "^7.21.4",
"@babel/plugin-transform-react-jsx-self": "^7.21.0",
"@babel/plugin-transform-react-jsx-source": "^7.19.6",
"magic-string": "^0.30.0",
"react-refresh": "^0.14.0"
},
"peerDependencies": {
Expand Down
47 changes: 7 additions & 40 deletions packages/plugin-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import type {
ResolvedConfig,
UserConfig,
} from 'vite'
import MagicString from 'magic-string'
import type { SourceMap } from 'magic-string'
import {
addRefreshWrapper,
preambleCode,
Expand All @@ -20,18 +18,17 @@ import {
export interface Options {
include?: string | RegExp | Array<string | RegExp>
exclude?: string | RegExp | Array<string | RegExp>
/**
* @deprecated All tools now support the automatic runtime, and it has been backported
* up to React 16. This allows to skip the React import and can produce smaller bundlers.
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic'
/**
* Control where the JSX factory is imported from.
* https://esbuild.github.io/api/#jsx-import-source
* @default 'react'
*/
jsxImportSource?: string
/**
* Note: Skipping React import with classic runtime is not supported from v4
* @default "automatic"
*/
jsxRuntime?: 'classic' | 'automatic'
/**
* Babel configuration applied in both dev and prod.
*/
Expand Down Expand Up @@ -82,7 +79,6 @@ declare module 'vite' {
}
}

const prependReactImportCode = "import React from 'react'; "
const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/
const defaultIncludeRE = /\.[tj]sx?$/
const tsRE = /\.tsx?$/
Expand All @@ -92,7 +88,6 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
let devBase = '/'
const filter = createFilter(opts.include ?? defaultIncludeRE, opts.exclude)
const devRuntime = `${opts.jsxImportSource ?? 'react'}/jsx-dev-runtime`
let needHiresSourcemap = false
let isProduction = true
let projectRoot = process.cwd()
let skipFastRefresh = false
Expand All @@ -105,7 +100,7 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
// - import * as React from 'react';
// - import React from 'react';
// - import React, {useEffect} from 'react';
const importReactRE = /(?:^|\n)import\s+(?:\*\s+as\s+)?React(?:,|\s+)/
const importReactRE = /(?:^|\s)import\s+(?:\*\s+as\s+)?React(?:,|\s+)/

const viteBabel: Plugin = {
name: 'vite:react-babel',
Expand All @@ -129,16 +124,9 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
configResolved(config) {
devBase = config.base
projectRoot = config.root
needHiresSourcemap =
config.command === 'build' && !!config.build.sourcemap
isProduction = config.isProduction
skipFastRefresh = isProduction || config.command === 'build'

if (opts.jsxRuntime === 'classic') {
config.logger.warnOnce(
'[@vitejs/plugin-react] Support for classic runtime is deprecated.',
)
}
if ('jsxPure' in opts) {
config.logger.warnOnce(
'[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly.',
Expand Down Expand Up @@ -191,7 +179,6 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
])
}

let prependReactImport = false
if (opts.jsxRuntime === 'classic' && isJSX) {
if (!isProduction) {
// These development plugins are only needed for the classic runtime.
Expand All @@ -200,24 +187,6 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
await loadPlugin('@babel/plugin-transform-react-jsx-source'),
)
}

// Even if the automatic JSX runtime is not used, we can still
// inject the React import for .jsx and .tsx modules.
if (!importReactRE.test(code)) {
prependReactImport = true
}
}

let inputMap: SourceMap | undefined
if (prependReactImport) {
if (needHiresSourcemap) {
const s = new MagicString(code)
s.prepend(prependReactImportCode)
code = s.toString()
inputMap = s.generateMap({ hires: true, source: id })
} else {
code = prependReactImportCode + code
}
}

// Avoid parsing if no special transformation is needed
Expand All @@ -226,7 +195,7 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
!babelOptions.configFile &&
!babelOptions.babelrc
) {
return { code, map: inputMap ?? null }
return
}

const parserPlugins = [...babelOptions.parserOpts.plugins]
Expand Down Expand Up @@ -256,8 +225,6 @@ export default function viteReact(opts: Options = {}): PluginOption[] {
},
plugins,
sourceMaps: true,
// Vite handles sourcemap flattening
inputSourceMap: inputMap ?? (false as any),
})

if (result) {
Expand Down
2 changes: 1 addition & 1 deletion playground/react-classic/App.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react'
import React, { useState } from 'react'

function App() {
const [count, setCount] = useState(0)
Expand Down
3 changes: 1 addition & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.