此預設(preset)始終包含以下插件:
如果開啟了 development 參數(shù),還將包含以下插件:
Classic runtime adds:
Automatic runtime (since v7.9.0) adds the functionality for these plugins automatically when the development option is enabled. If you have automatic runtime enabled, adding @babel/plugin-transform-react-jsx-self or @babel/plugin-transform-react-jsx-source will error.
注意:在 v7 版本中將不再開啟對 Flow 語法的支持。如果仍需支持,需要添加 Flow preset。
你還可以查看 React 的 入門指南。
pnpm add --save-dev @babel/preset-react
不帶參數(shù):
babel.config.json
{
"presets": ["@babel/preset-react"]
}
帶參數(shù):
babel.config.json
{
"presets": [
[
"@babel/preset-react",
{
"pragma": "dom", // default pragma is React.createElement (only in classic runtime)
"pragmaFrag": "DomFrag", // default is React.Fragment (only in classic runtime)
"throwIfNamespace": false, // defaults to true
"runtime": "classic" // defaults to classic
// "importSource": "custom-jsx-library" // defaults to react (only in automatic runtime)
}
]
]
}
Shell
babel --presets @babel/preset-react script.js
JavaScript
require("@babel/core").transformSync("code", {
presets: ["@babel/preset-react"],
});
classic | automatic,默認值為 classic
添加于: v7.9.0
用于決定使用哪個運行時。
當設置為 automatic 時,將自動導入(import)JSX 轉換而來的函數(shù)。當設置為 classic 時,不會自動導入(import)任何東西。
boolean 類型,默認值為 false.
這可以用于開啟特定于開發(fā)環(huán)境的某些行為,例如添加 __source 和 __self。
在與 env 參數(shù) 配置或 js 配置文件 配合使用時,此功能很有用。
boolean, defaults to true.
Toggles whether or not to throw an error if a XML namespaced tag name is used. For example:
<f:image />
雖然 JSX 規(guī)范允許這樣做,但是默認情況下是被禁止的,因為 React 所實現(xiàn)的 JSX 目前并不支持這種方式。
boolean, defaults to true.
Enables @babel/plugin-transform-react-pure-annotations. It will mark top-level React method calls as pure for tree shaking.
string 類型,默認值為 true。
添加于: v7.9.0
Replaces the import source when importing functions.
string, defaults to React.createElement.
Replace the function used when compiling JSX expressions. It should be a qualified name (e.g. React.createElement) or an identifier (e.g. createElement).
string, defaults to React.Fragment.
Replace the component used when compiling JSX fragments. It should be a valid JSX tag name.
boolean, defaults to false.
Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.
boolean, defaults to false.
Added in: v7.7.0
When spreading props, use inline object with spread elements directly instead of Babel's extend helper or Object.assign.
babel.config.js
module.exports = {
presets: [
[
"@babel/preset-react",
{
development: process.env.BABEL_ENV === "development",
},
],
],
};
注意: env 參數(shù)可能很快將被廢棄
babel.config.json
{
"presets": ["@babel/preset-react"],
"env": {
"development": {
"presets": [["@babel/preset-react", { "development": true }]]
}
}
}
You can read more about configuring preset options here
更多建議: