一、Bable使用
Babel是一个工具链,主要用于将ECMAScript 2015+的代码转化为在当前和旧版本的浏览器或环境中向后兼容的JavaScript版本。能够做到转换语法、通过 Polyfill 方式在目标环境中添加缺失的特性(通过bable/polyfill)、源代码转换等等。
转码前:
[1, 2, 3].map((n) => n + 1);
转码后:
[1, 2, 3].map(function(n) {
return n + 1;
});
Plugins(插件)
转换以插件的形式出现,插件是小型JavaScript程序,它指示Babel如何对代码进行转换。
1.转换插件&语法插件
转换插件将启用相应的语法插件,因此你不必同时指定这两种插件
(1)转换插件用来转换代码:
ES3
-
babel-plugin-transform-member-expression-literals
-
babel-plugin-transform-property-literals
-
@babel/plugin-transform-reserved-words
ES5
- @babel/plugin-transform-property-mutators
ES2015
- @babel/plugin-transform-arrow-functions
- @babel/plugin-transform-block-scoped-functions
- @babel/plugin-transform-block-scoping
- @babel/plugin-transform-classes
- @babel/plugin-transform-computed-properties
- @babel/plugin-transform-destructuring
- @babel/plugin-transform-duplicate-keys
- @babel/plugin-transform-for-of
- @babel/plugin-transform-function-name
- @babel/plugin-transform-instanceof
- @babel/plugin-transform-literals
- @babel/plugin-transform-new-target
- @babel/plugin-transform-object-super
- @babel/plugin-transform-parameters
- @babel/plugin-transform-shorthand-properties
- @babel/plugin-transform-spread
- @babel/plugin-transform-sticky-regex
- @babel/plugin-transform-template-literals
- @babel/plugin-transform-typeof-symbol
- @babel/plugin-transform-unicode-regex
ES2016
- @babel/plugin-transform-exponentiation-operator
ES2017
- @babel/plugin-transform-async-to-generator
ES2018
- @babel/plugin-proposal-async-generator-functions
- @babel/plugin-transform-dotall-regex
- @babel/plugin-transform-named-capturing-groups-regex
- @babel/plugin-proposal-object-rest-spread
- @babel/plugin-proposal-optional-catch-binding
- @babel/plugin-proposal-unicode-property-regex
Modules
- @babel/plugin-transform-modules-amd
- @babel/plugin-transform-modules-commonjs
- @babel/plugin-transform-modules-systemjs
- @babel/plugin-transform-modules-umd
Experimental
- @babel/plugin-proposal-class-properties
- @babel/plugin-proposal-decorators
- @babel/plugin-proposal-do-expressions
- @babel/plugin-proposal-export-default-from
- @babel/plugin-proposal-export-namespace-from
- @babel/plugin-proposal-function-bind
- @babel/plugin-proposal-function-sent
- @babel/plugin-proposal-logical-assignment-operators
- @babel/plugin-proposal-nullish-coalescing-operator
- @babel/plugin-proposal-numeric-separator
- @babel/plugin-proposal-optional-chaining
- @babel/plugin-proposal-partial-application
- @babel/plugin-proposal-pipeline-operator
- @babel/plugin-proposal-private-methods
- @babel/plugin-proposal-throw-expressions
Minification
- babel-plugin-transform-inline-consecutive-adds
- babel-plugin-transform-inline-environment-variables
- babel-plugin-transform-member-expression-literals
- babel-plugin-transform-merge-sibling-variables
- babel-plugin-transform-minify-booleans
- babel-plugin-minify-builtins
- babel-plugin-minify-constant-folding
- babel-plugin-minify-dead-code-elimination
- babel-plugin-minify-flip-comparisons
- babel-plugin-minify-guarded-expressions
- babel-plugin-minify-infinity
- babel-plugin-minify-mangle-names
- babel-plugin-minify-numeric-literals
- babel-plugin-minify-replace
- babel-plugin-minify-simplify
- babel-plugin-minify-type-constructors
- babel-plugin-transform-node-env-inline
- babel-plugin-transform-property-literals
- babel-plugin-transform-regexp-constructors
- babel-plugin-transform-remove-console
- babel-plugin-transform-remove-debugger
- babel-plugin-transform-remove-undefined
- babel-plugin-transform-simplify-comparison-operators
- babel-plugin-transform-undefined-to-void
React
- @babel/plugin-transform-react-constant-elements
- @babel/plugin-transform-react-display-name
- @babel/plugin-transform-react-inline-elements
- @babel/plugin-transform-react-jsx
- @babel/plugin-transform-react-jsx-compat
- @babel/plugin-transform-react-jsx-self
- @babel/plugin-transform-react-jsx-source
其他
- @babel/plugin-external-helpers
- @babel/plugin-transform-flow-strip-types
- @babel/plugin-transform-jscript
- @babel/plugin-transform-object-assign
- @babel/plugin-transform-object-set-prototype-of-to-assign
- @babel/plugin-transform-proto-to-assign
- @babel/plugin-transform-regenerator
- @babel/plugin-transform-runtime
- @babel/plugin-transform-strict-mode
- @babel/plugin-transform-typescript
(2)语法插件只允许 Babel 解析(parse)特定类型的语法(而不是转换)
.babelrc
{
"parserOpts": {
"plugins": ["jsx", "flow"]
}
}
2.Plugins配置可以省略前缀babel-plugin-
{
"plugins": [
"myPlugin",
"babel-plugin-myPlugin" // equivalent
]
}
3.Plugins执行顺序
- 插件在预设之前运行
- 插件从前往后执行
- 预设顺序相反(从后往前)
4.Plugins路径
{
"plugins": ["babel-plugin-myPlugin"]
}
也可以指定相对/绝对路径
{
"plugins": ["./node_modules/asdf/plugin"]
}
只有使用了相应的插件Babel才能做相应的转换,所以需要一一添加需要的插件很麻烦,这个时候我们就可以使用Presets的形式启用一组插件
Presets(预设)
官方给我们提供了一些常用的Presets:
1.Presets路径
{
"presets": ["babel-preset-myPreset"]
}
您还可以指定Presets的相对/绝对路径
{
"presets": ["./myProject/myPreset"]
}
2.如果包的名称带有前缀babel-preset-,可以使用简写
{
"presets": [
"myPreset",
"babel-preset-myPreset" // equivalent
]
}
3.Presets执行顺序
{
"presets": [
"a",
"b",
"c"
]
}
上述代码将按照以下顺序执行:c,b,然后a
二、Babel配置文件
1.babel.config.js
以编程的方式创建配置文件并编译 node_modules
目录下的模块
在项目的根目录(package.json
文件所在目录)下创建一个名为 babel.config.js
的文件,并输入如下内容
module.exports = function (api) {
api.cache(true);
const presets = [ ... ];
const plugins = [ ... ];
return {
presets,
plugins
};
}
2..babelrc
(and .babelrc.js
) files
在你的项目中创建名为 .babelrc
的文件,并输入以下内容
{
"presets": [...],
"plugins": [...]
}
.babelrc.js文件与 .babelrc
的配置相同,但你可以使用 JavaScript 编写
const presets = [ ... ];
const plugins = [ ... ];
module.exports = { presets, plugins };
你还可以调用 Node.js 的任何 API,例如基于进程环境进行动态配置
const presets = [ ... ];
const plugins = [ ... ];
if (process.env["ENV"] === "prod") {
plugins.push(...);
}
module.exports = { presets, plugins };
3.package.json
files with a "babel"
key
将 .babelrc
中的配置信息作为 babel
键(key)的值添加到 package.json
文件中,如下所示
{
"name": "my-package",
"version": "1.0.0",
"babel": {
"presets": [ ... ],
"plugins": [ ... ],
}
}
三、@babel/core API
1.安装
npm install --save-dev @babel/core
2.引入
var babel = require("@babel/core");
import { transform } from "@babel/core";
import * as babel from "@babel/core";
3.常用方法
/**
* babel.transform(code: string, options?: Object, callback: Function)
*/
babel.transform("code();", options, function(err, result) {
result.code;
result.map;
result.ast;
});
/**
* babel.transformSync(code: string, options?: Object)
*/
var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;
/**
* babel.transformAsync(code: string, options?: Object)
*/
babel.transformAsync("code();", options).then(result => {
result.code;
result.map;
result.ast;
});
/**
* babel.transformFile(filename: string, options?: Object, callback: Function)
*/
babel.transformFile("filename.js", options, function (err, result) {
result; // => { code, map, ast }
});
/**
* babel.transformFileSync(filename: string, options?: Object)
*/
babel.transformFileSync("filename.js", options).code;
/**
* babel.transformFileAsync(filename: string, options?: Object)
*/
babel.transformFileAsync("filename.js", options).then(result => {
result.code;
});
/**
* babel.transformFromAst(ast: Object, code?: string, options?: Object, callback: Function): FileNode | null
*/
const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
const { code, map, ast } = result;
});
/**
* babel.transformFromAstSync(ast: Object, code?: string, options?: Object)
*/
const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
const { code, map, ast } = babel.transformFromAstSync(parsedAst, sourceCode, options);
/**
* babel.transformFromAstAsync(ast: Object, code?: string, options?: Object)
*/
const sourceCode = "if (true) return;";
babel.parseAsync(sourceCode, { allowReturnOutsideFunction: true })
.then(parsedAst => {
return babel.transformFromAstSync(parsedAst, sourceCode, options);
})
.then(({ code, map, ast }) => {
// ...
});
四、@babel/cli命令行工具
1.安装
npm install --save-dev @babel/core @babel/cli
2.用法
(1)编译文件
babel script.js
npx babel script.js
npx babel script.js --out-file script-compiled.js
npx babel script.js --watch --out-file script-compiled.js
(2)编译并输出源码映射表
npx babel script.js --out-file script-compiled.js --source-maps
npx babel script.js --out-file script-compiled.js --source-maps inline
(3)编译整个目录
npx babel src --out-dir lib
npx babel src --out-file script-compiled.js
(4)忽略某些文件
npx babel src --out-dir lib --ignore "src/**/*.spec.js","src/**/*.test.js"
(5)拷贝文件
npx babel src --out-dir lib --copy-files
(6)通过管道输入文件
npx babel --out-file script-compiled.js < script.js
(7)使用插件
npx babel script.js --out-file script-compiled.js --plugins=@babel/proposal-class-properties,@babel/transform-modules-amd
(8)使用 Preset
npx babel script.js --out-file script-compiled.js --presets=@babel/preset-env,@babel/flow
(9)忽略 .babelrc 文件
npx babel --no-babelrc script.js --out-file script-compiled.js --presets=es2015,react