变化对比
旧模式下,需要import React 打包工具才能正常编译
import React from 'react';
function App() {
return <h1>Hello World</h1>;
}
全新的JSX编译模式支持以下写法:
function App() {
return <h1>Hello World</h1>;
}
React更新引入了 react/jsx-runtime,编译工具会自动到React模块中获取并将代码编译为,而不是以前的React.createElement,更多详细内容可查看官方博客-介绍全新的 JSX 转换
// 由编译器引入(禁止自己引入!)
import {jsx as _jsx} from 'react/jsx-runtime';
function App() {
return _jsx('h1', { children: 'Hello world' });
}
如何配置项目
附带删除 后的错误示例与配置修复import React from 'react';
ESlint 配置
/* eslint-disable no-undef */
module.exports = {
parserOptions: {
...
ecmaFeatures: {
jsx: true, // 启用JSX
},
},
extends: [
...
'plugin:react/jsx-runtime', // 启用新jsx规则
],
rules: {
...
'react/jsx-uses-react': 'off', // 关闭旧模式校验
'react/react-in-jsx-scope': 'off', // 关闭旧模式校验
},
}
babel 配置
@babel/preset-react编译增加 runtime: 'automatic'配置,其他编译预设可查看React官方文档说明,automatic配置相关说明可查看Babel @babel/preset-react 文档
module.exports = {
presets: [
[
'@babel/preset-react',
{
runtime: 'automatic',
},
],
'@babel/preset-typescript',
],
plugins: ['react-refresh/babel'],
}
在babel的json或js文件中配置插件 react-refresh/babel可能会导致编译后项目访问报错 # $RefreshReg$ is not defined react,点击此处查看解决方案
Typescript 的tsconfig.json配置
将jsx
react修改为 react-jsx,配置详情可查看TS官方文档说明
{
// 编译规则
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"target": "es5",
// "jsx": "react",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules"]
}