依赖安装
首先需要安装 babel 编译需的模块,包括 babel-core
和 babel-preset-env
npm i -D babel-core babel-preset-env
webpack 配置 babel-loader
// webpack.config.jsmodule: { rules: [ { test: /\.js$/, exclude: "/node_modules/", use: { loader: "babel-loader", }, }, ];}
配置.babelrc
{ "presets": [["babel-preset-env"]]}
到这里就配置完 babel 了,可以试着看下编译下面的文件
let [a, ...b] = [1, 2, 3, 4];console.log(a, b);class Bird { constructor(name) { this.name = name; } say() { alert(`I'm ${this.name}`); }}let bird = new Bird("Hasaki");bird.say();
上述文件生成对应的 es5 代码
eval( "\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar a = 1,\n b = [2, 3, 4];\n\nconsole.log(a, b);\n\nvar Bird = function () {\n function Bird(name) {\n _classCallCheck(this, Bird);\n\n this.name = name;\n }\n\n _createClass(Bird, [{\n key: 'say',\n value: function say() {\n alert('I\\'m ' + this.name);\n }\n }]);\n\n return Bird;\n}();\n\nvar bird = new Bird('Hasaki');\nbird.say();\n\n//# sourceURL=webpack:///./index.js?");
babel 插件
babel 不仅可以转化 es6 代码,还可以转化一些 es7 的代码,可以借助插件来实现,例如在 es7 里面有 do 表达式
安装插件
npm i -D babel-plugin-transform-do-expressions
配置.babelrc
"plugins": [ "transform-do-expressions"]
编译下面代码
let a = 1;let foo = do { if (a === 1) { ("Yes"); } else { ("No"); }};alert(foo); // 弹出yes
do 表达式在 jsx 很有用,例如需要条件返回对应的组件,由于不能在块语句里条件判断返回值,会用一个函数去判断返回,例如
const getColoredComponent = (color) => { if (color === "blue") { return <BlueComponent />; } if (color === "red") { return <RedComponent />; } if (color === "green") { return <GreenComponent />; }};const Component = (props) => <div className="myComponent">{getColoredComponent()}</div>;
使用 do,就不需要再声明一个函数来实现
const Component = (props) => ( <div className="myComponent"> {do { if (color === "blue") { <BlueComponent />; } else if (color === "red") { <RedComponent />; } else if (color === "green") { <GreenComponent />; } }} </div>);
除了上面的插件,官方还列出了各种插件,基本满足 es6 的语法,可在此 网站 寻找合适的插件来使用