參數(shù)可以通過(guò)多種方式 傳遞給 Babel。當(dāng)直接傳遞給 Babel 時(shí), 你可以只傳遞參數(shù)對(duì)象。當(dāng) Babel is used via a wrapper, it may also be necessary, or at least more useful, to pass the options via configuration files.
如果通過(guò) @babel/cli 傳遞參數(shù)時(shí),你需要將參數(shù)名按照 kebab-case(短橫線連接)方式做轉(zhuǎn)換。例如:
npx babel --root-mode upward file.js # 等價(jià)于 rootMode 參數(shù)
以下這些參數(shù)僅在以編程方式調(diào)用 Babel 時(shí)使用,因此, 以下這些參數(shù)主要被用于第三方工具或者用戶直接調(diào)用 babel.transform 函數(shù)時(shí)。對(duì)于使用集成 Babel 工具的用戶,例如 babel-loader 或 @babel/register ,不會(huì)用到以下這些參數(shù)的。
類型: string默認(rèn)值: process.cwd()
當(dāng)前工作目錄。所有以編程方式傳遞進(jìn)來(lái)的路徑都 相對(duì)于當(dāng)前工作目錄開(kāi)始解析。
類型: 具有如下類型的對(duì)象
interface CallerData {
name: string;
supportsStaticESM?: boolean;
supportsDynamicImport?: boolean;
supportsTopLevelAwait?: boolean;
supportsExportNamespaceFrom?: boolean;
}
Utilities may pass a caller object to identify themselves to Babel and pass capability-related flags for use by configs, presets and plugins. For example
JavaScript
babel.transformFileSync("example.js", {
caller: {
name: "my-custom-tool",
supportsStaticESM: true,
},
});
would allow plugins and presets to decide that, since ES modules are supported, they will skip compilation of ES modules into CommonJS modules.
類型: string
需要編譯的源碼文件的文件名(可以沒(méi)有)。 filename 參數(shù)是可選的,但是當(dāng)文件名未知時(shí),并不是所有的 Babel 功能都可用, 因?yàn)槟承﹨?shù)依賴 filename 參數(shù) 來(lái)實(shí)現(xiàn)其功能。
用戶可能遇到的三種主要情況是:
Type: stringDefault: path.relative(opts.cwd, opts.filename) (if "filename" was passed)
Used as the default value for Babel's sourceFileName option, and used as part of generation of filenames for the AMD / UMD / SystemJS module transforms.
類型: boolean默認(rèn)值: true
Babel's default return value includes code and map properties with the resulting generated code. In some contexts where multiple calls to Babel are being made, it can be helpful to disable code generation and instead use ast: true to get the AST directly in order to avoid doing unnecessary work.
Type: booleanDefault: false
Babel's default is to generate a string and a sourcemap, but in some contexts it can be useful to get the AST itself. The primary use case for this would be a chain of multiple transform passes, along the lines of
JavaScript
const filename = "example.js";
const source = fs.readFileSync(filename, "utf8");
// Load and compile file normally, but skip code generation.
const { ast } = babel.transformSync(source, {
filename,
ast: true,
code: false,
});
// Minify the file in a second pass and generate the output code here.
const { code, map } = babel.transformFromAstSync(ast, source, {
filename,
presets: ["minify"],
babelrc: false,
configFile: false,
});
Note: This option is not on by default because the majority of users won't need it and because we'd like to eventually add a caching layer to Babel. Having to cache the AST structure will take significantly more space.
Type: booleanDefault: trueAdded in v7.11.0
By default babel.transformFromAst will clone the input AST to avoid mutations. Specifying cloneInputAst: false can improve parsing performance if the input AST is not used elsewhere.
Loading configuration can get a little complex as environments can have several types of configuration files, and those configuration files can have various nested configuration objects that apply depending on the configuration.
Type: stringDefault: opts.cwdPlacement: Only allowed in Babel's programmatic options
The initial path that will be processed based on the "rootMode" to determine the conceptual root folder for the current Babel project. This is used in two primary cases:
Type: "root" | "upward" | "upward-optional"Default: "root"Placement: Only allowed in Babel's programmatic optionsAdded in: v7.1.0
This option, combined with the "root" value, defines how Babel chooses its project root. The different modes define different ways that Babel can process the "root" value to get the final project root.
Note: babel.config.json is supported from Babel 7.8.0. In older Babel 7 versions, only babel.config.js is supported.
"root" is the default mode because it avoids the risk that Babel will accidentally load a babel.config.json that is entirely outside of the current project folder. If you use "upward-optional", be aware that it will walk up the directory structure all the way to the filesystem root, and it is always possible that someone will have a forgotten babel.config.json in their home directory, which could cause unexpected errors in your builds.
Users with monorepo project structures that run builds/tests on a per-package basis may well want to use "upward" since monorepos often have a babel.config.json in the project root. Running Babel in a monorepo subdirectory without "upward", will cause Babel to skip loading any babel.config.json files in the project root, which can lead to unexpected errors and compilation failure.
Type: stringDefault: process.env.BABEL_ENV || process.env.NODE_ENV || "development"Placement: Only allowed in Babel's programmatic options
The current active environment used during configuration loading. This value is used as the key when resolving "env" configs, and is also available inside configuration functions, plugins, and presets, via the api.env() function.
Type: string | booleanDefault: path.resolve(opts.root, "babel.config.json"), if it exists, false otherwisePlacement: Only allowed in Babel's programmatic options
Defaults to searching for a default babel.config.json file, but can be passed the path of any JS or JSON5 config file.
NOTE: This option does not affect loading of .babelrc.json files, so while it may be tempting to do configFile: "./foo/.babelrc.json", it is not recommended. If the given .babelrc.json is loaded via the standard file-relative logic, you'll end up loading the same config file twice, merging it with itself. If you are linking a specific config file, it is recommended to stick with a naming scheme that is independent of the "babelrc" name.
Type: booleanDefault: true as long as the filename option has been specifiedPlacement: Allowed in Babel's programmatic options, or inside of the loaded "configFile". A programmatic option will override a config file one.
true will enable searching for configuration files relative to the "filename" provided to Babel.
A babelrc value passed in the programmatic options will override one set within a configuration file.
Note: .babelrc.json files are only loaded if the current "filename" is inside of a package that matches one of the "babelrcRoots" packages.
Type: boolean | MatchPattern | Array<MatchPattern>Default: opts.rootPlacement: Allowed in Babel's programmatic options, or inside of the loaded configFile. A programmatic option will override a config file one.
By default, Babel will only search for .babelrc.json files within the "root" package because otherwise Babel cannot know if a given .babelrc.json is meant to be loaded, or if it's "plugins" and "presets" have even been installed, since the file being compiled could be inside node_modules, or have been symlinked into the project.
This option allows users to provide a list of other packages that should be considered "root" packages when considering whether to load .babelrc.json files.
For example, a monorepo setup that wishes to allow individual packages to have their own configs might want to do
JavaScript
babelrcRoots: [
// Keep the root as a root
".",
// Also consider monorepo packages "root" and load their .babelrc.json files.
"./packages/*",
];
Type: Array<PluginEntry | Plugin> (PluginEntry)Default: []
An array of plugins to activate when processing this file. For more information on how individual entries interact, especially when used across multiple nested "env" and "overrides" configs, see merging.
Note: The option also allows Plugin instances from Babel itself, but using these directly is not recommended. If you need to create a persistent representation of a plugin or preset, you should use babel.createConfigItem().
Type: Array<PresetEntry> (PresetEntry)Default: []
An array of presets to activate when processing this file. For more information on how individual entries interact, especially when used across multiple nested "env" and "overrides" configs, see merging.
Note: The format of presets is identical to plugins, except for the fact that name normalization expects "preset-" instead of "plugin-", and presets cannot be instances of Plugin.
Type: booleanDefault: falseStatus: Deprecated
Instructs Babel to run each of the presets in the presets array as an independent pass. This option tends to introduce a lot of confusion around the exact ordering of plugins, but can be useful if you absolutely need to run a set of operations as independent compilation passes.
Note: This option may be removed in future Babel versions as we add better support for defining ordering between plugins.
Type: string | Array<string> | { [string]: string }Default: {}Placement: Allowed in Babel's programmatic options, or in config filesAdded in: v7.13.0
Describes the environments you support/target for your project.
This can either be a browserslist-compatible query (with caveats):
babel.config.json
{
"targets": "> 0.25%, not dead"
}
Or an object of minimum environment versions to support:
babel.config.json
{
"targets": {
"chrome": "58",
"ie": "11"
}
}
Supported environments: android, chrome, deno, edge, electron, firefox, ie, ios, node, opera, rhino, safari, samsung.
If a minor version is not specified, Babel will interpret it as MAJOR.0. For example, "node": 12 will be considered as Node.js 12.0.
When no targets are specified: Babel will assume you are targeting the oldest browsers possible. For example, @babel/preset-env will transform all ES2015-ES2020 code to be ES5 compatible.
We recommend setting targets to reduce the output code size.
babel.config.json
{
"presets": ["@babel/preset-env"]
}
Because of this, Babel's behavior is different than browserslist: it does not use the defaults query when there are no targets are found in your Babel or browserslist config(s). If you want to use the defaults query, you will need to explicitly pass it as a target:
babel.config.json
{
"targets": "defaults"
}
We recognize this isn’t ideal and will be revisiting this in Babel v8.
Type: boolean
You may also target browsers supporting ES Modules (https://www.ecma-international.org/ecma-262/6.0/#sec-modules). When the esmodules target is specified, it will intersect with the browsers target and browserslist's targets. You can use this approach in combination with <script type="module"></script> to conditionally serve smaller scripts to users (https://jakearchibald.com/2017/es-modules-in-browsers/#nomodule-for-backwards-compatibility).
Please note: when specifying both browsers and the esmodules target, they will be intersected.
babel.config.json
{
"targets": {
"esmodules": true
}
}
Type: string | "current" | true.
If you want to compile against the current node version, you can specify "node": true or "node": "current", which would be the same as "node": process.versions.node.
Alternatively, you can specify the node version in a browserslist query:
babel.config.json
{
"targets": "node 12" // not recommended
}
In this case, browserslist will resolve it to the latest version available in the node-releases library. Because Node.js may support new language features in minor releases, a program generated for Node.js 12.22 may throw a syntax error on Node.js 12.0. We recommend that you always specify a minor version when using node queries with browserslist:
babel.config.json
{
"targets": "node 12.0"
}
Type: string | "tp".
If you want to compile against the technology preview version of Safari, you can specify "safari": "tp".
Type: string | Array<string>.
A query to select browsers (ex: last 2 versions, > 5%, safari tp) using browserslist.
Note, browsers' results are overridden by explicit items from targets.
Type: string.
The minimum supported version is 1.0.
babel.config.json
{
"targets": {
"deno": "1.9"
}
}
Type: booleanDefault: truePlacement: Allowed in Babel's programmatic options, or in config filesAdded in: v7.13.0
Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json. This is useful for projects that use a browserslist config for files that won't be compiled with Babel.
If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies this option, or to cwd when it's passed as part of the programmatic options.
Type: stringDefault: undefinedPlacement: Allowed in Babel's programmatic options, or in config filesAdded in: v7.13.0
The Browserslist environment to use.
Type: stringPlacement: Not allowed inside of presets
Configs may "extend" other configuration files. Config fields in the current config will be merged on top of the extended file's configuration.
Type: { [envKey: string]: Options }Placement: May not be nested inside of another env block.
Allows for entire nested configuration options that will only be enabled if the envKey matches the envName option.
Note: env[envKey] options will be merged on top of the options specified in the root object.
Type: Array<Options>Placement: May not be nested inside of another overrides object, or within an env block.
Allows users to provide an array of options that will be merged into the current configuration one at a time. This feature is best used alongside the "test"/ "include"/"exclude" options to provide conditions for which an override should apply. For example:
JavaScript
overrides: [{
test: "./vendor/large.min.js",
compact: true,
}],
could be used to enable the compact option for one specific file that is known to be large and minified, and tell Babel not to bother trying to print the file nicely.
Type: MatchPattern | Array<MatchPattern> (MatchPattern)
If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing. This option is most useful when used within an overrides option object, but it's allowed anywhere.
Note: These toggles do not affect the programmatic and config-loading options in earlier sections, since they are taken into account long before the configuration that is prepared for merging.
Type: MatchPattern | Array<MatchPattern> (MatchPattern)
This option is a synonym for "test".
Type: MatchPattern | Array<MatchPattern> (MatchPattern)
If any of patterns match, the current configuration object is considered inactive and is ignored during config processing. This option is most useful when used within an overrides option object, but it's allowed anywhere.
Note: These toggles do not affect the programmatic and config-loading options in earlier sections, since they are taken into account long before the configuration that is prepared for merging.
Type: Array<MatchPattern> (MatchPattern)Placement: Not allowed inside of presets
If any of the patterns match, Babel will immediately stop all processing of the current build. For example, a user may want to do something like
JavaScript
ignore: ["./lib"];
to explicitly disable Babel compilation of files inside the lib directory.
Note: This option disables all Babel processing of a file. While that has its uses, it is also worth considering the "exclude" option as a less aggressive alternative.
Type: Array<MatchPattern> (MatchPattern)Placement: Not allowed inside of presets
If all of the patterns fail to match, Babel will immediately stop all processing of the current build. For example, a user may want to do something like
JavaScript
only: ["./src"];
to explicitly enable Babel compilation of files inside the src directory while disabling everything else.
Note: This option disables all Babel processing of a file. While that has its uses, it is also worth considering the "test"/"include" options as a less aggressive alternative.
Type: boolean | SourceMapDefault: true
true will attempt to load an input sourcemap from the file itself, if it contains a //# sourceMappingURL=... comment. If no map is found, or the map fails to load and parse, it will be silently discarded.
If an object is provided, it will be treated as the source map object itself.
Type: boolean | "inline" | "both"Default: false
@babel/cli overloads some of these to also affect how maps are written to disk:
Note: These options are bit weird, so it may make the most sense to just use true and handle the rest in your own code, depending on your use case.
This is an synonym for sourceMaps. Using sourceMaps is recommended.
Type: stringDefault: path.basename(opts.filenameRelative) when available, or "unknown"
The name to use for the file inside the source map object.
Type: string
The sourceRoot fields to set in the generated source map, if one is desired.
Type: "script" | "module" | "unambiguous"Default: "module"
unambiguous can be quite useful in contexts where the type is unknown, but it can lead to false matches because it's perfectly valid to have a module file that does not use import/export statements.
This option is important because the type of the current file affects both parsing of input files, and certain transforms that may wish to add import/require usage to the current file.
For instance, @babel/plugin-transform-runtime relies on the type of the current document to decide whether to insert an import declaration, or a require() call. @babel/preset-env also does the same for its "useBuiltIns" option. Since Babel defaults to treating files are ES modules, generally these plugins/presets will insert import statements. Setting the correct sourceType can be important because having the wrong type can lead to cases where Babel would insert import statements into files that are meant to be CommonJS files. This can be particularly important in projects where compilation of node_modules dependencies is being performed, because inserting an import statements can cause Webpack and other tooling to see a file as an ES module, breaking what would otherwise be a functional CommonJS file.
Note: This option will not affect parsing of .mjs files, as they are currently hard-coded to always parse as "module" files.
Type: { [assumption: string]: boolean }Default: {}Added in: v7.13.0Placement: Allowed in programmatic options, config files and presets.
Set assumptions that Babel can make in order to produce smaller output:
babel.config.json
{
"assumptions": {
"iterableIsArray": true
},
"presets": ["@babel/preset-env"]
}
For more informations, check the assumptions documentation page.
Type: booleanDefault: true
Highlight tokens in code snippets in Babel's error messages to make them easier to read.
Type: (key: string, nodeType: string, fn: Function) => Function
Allows users to add a wrapper on each visitor in order to inspect the visitor process as Babel executes the plugins.
Users can return a replacement function that should call the original function after performing whatever logging and analysis they wish to do.
Type: {}
An opaque object containing options to pass through to the parser being used.
For available parser options, see Parser Options.
Type: {}
An opaque object containing options to pass through to the code generator being used. See Code Generator Options for most used options.
Type: booleanDefault: false
Babel will make an effort to generate code such that items are printed on the same line that they were on in the original file. This option exists so that users who cannot use source maps can get vaguely useful error line numbers, but it is only a best-effort, and is not guaranteed in all cases with all plugins.
Type: boolean | "auto"Default: "auto"
"auto" will set the value by evaluating code.length > 500_000
All optional newlines and whitespace will be omitted when generating code in compact mode.
Type: booleanDefault: false
Includes compact: true, omits block-end semicolons, omits () from new Foo() when possible, and may output shorter versions of literals.
Type: string
Allows specifying a prefix comment to insert before pieces of code that were not present in the original file.
Note: The definition of what is and isn't present in the original file can get a little ugly, so usage of this option is not recommended. If you need to annotate code somehow, it is better to do so using a Babel plugin.
Type: string
Allows specifying a prefix comment to insert after pieces of code that were not present in the original file.
Note: The definition of what is and isn't present in the original file can get a little ugly, so usage of this option is not recommended. If you need to annotate code somehow, it is better to do so using a Babel plugin.
Type: booleanDefault: true
Provides a default comment state for shouldPrintComment if no function is given. See the default value of that option for more info.
Type: (value: string) => booleanDefault without minified: (val) => opts.comments || /@license|@preserve/.test(val)Default with minified: () => opts.comments
A function that can decide whether a given comment should be included in the output code from Babel.
For more code generator options, see Generator Options.
Type: booleanDefault: !!opts.moduleId
Enables module ID generation.
Type: string
A hard-coded ID to use for the module. Cannot be used alongside getModuleId.
Type: (name: string) => string
Given the babel-generated module name, return the name to use. Returning a falsy value will use the original name.
Type: string
A root path to include on generated module names.
Type: string | RegExp | (filename: string | void, context: { caller: { name: string } | void, envName: string, dirname: string ) => boolean
Several Babel options perform tests against file paths. In general, these options support a common pattern approach where each pattern can be
Importantly, if either of these are used, Babel requires that the filename option be present, and will consider it an error otherwise.
Please refer to How Babel merges config items.
Individual plugin/preset items can have several different structures:
The same EntryTarget may be used multiple times unless each one is given a different name, and doing so will result in a duplicate-plugin/preset error.
That can be a little hard to read, so as an example:
JavaScript
plugins: [
// EntryTarget
'@babel/plugin-transform-classes',
// [EntryTarget, EntryOptions]
['@babel/plugin-transform-arrow-functions', { spec: true }],
// [EntryTarget, EntryOptions, string]
['@babel/plugin-transform-for-of', { loose: true }, "some-name"],
// ConfigItem
babel.createConfigItem(require("@babel/plugin-transform-spread")),
],
Type: string | {} | Function
A plugin/preset target can come from a few different sources:
Type: undefined | {} | false
Options are passed through to each plugin/preset when they are executed. undefined will be normalized to an empty object.
false indicates that an entry is entirely disabled. This can be useful in contexts where ordering is important, but a separate condition is needed to decide if something is enabled. For instance:
JavaScript
plugins: [
'one',
['two', false],
'three',
],
overrides: [{
test: "./src",
plugins: [
'two',
]
}]
would enable the two plugin for files in src, but two would still execute between one and three.
By default, Babel expects plugins to have a babel-plugin- or babel-preset- prefix in their name. To avoid repetition, Babel has a name normalization phase will automatically add these prefixes when loading items. This boils down to a few primary rules:
Here are some examples, when applied in a plugin context:
Input | Normalized |
---|---|
"/dir/plugin.js"
|
"/dir/plugin.js"
|
"./dir/plugin.js"
|
"./dir/plugin.js"
|
"mod"
|
"babel-plugin-mod"
|
"mod/plugin"
|
"mod/plugin"
|
"babel-plugin-mod"
|
"babel-plugin-mod"
|
"@babel/mod"
|
"@babel/plugin-mod"
|
"@babel/plugin-mod"
|
"@babel/plugin-mod"
|
"@babel/mod/plugin"
|
"@babel/mod/plugin"
|
"@scope"
|
"@scope/babel-plugin"
|
"@scope/babel-plugin"
|
"@scope/babel-plugin"
|
"@scope/mod"
|
"@scope/babel-plugin-mod"
|
"@scope/babel-plugin-mod"
|
"@scope/babel-plugin-mod"
|
"@scope/prefix-babel-plugin-mod"
|
"@scope/prefix-babel-plugin-mod"
|
"@scope/mod/plugin"
|
"@scope/mod/plugin"
|
"module:foo"
|
"foo"
|
更多建議: