依赖安装

首先需要安装 babel 编译需的模块,包括 babel-corebabel-preset-env

npm i -D babel-core babel-preset-env

webpack配置babel-loader

// webpack.config.js
module: {
  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的语法,可在此 网站 寻找合适的插件来使用

本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系340443366@qq.com
标签: Javascript webpack