作用

将新的语法转换为老的语法。

安装

  1. npm i babel-loader @babel/core @babel/preset-env webpack -D

如果需要支持更加高级的ES6语法,可以安装以下插件:

  1. npm i @babel/plugin-proposal-class-properties -D

:::warning @babel/plugin-proposal-class-properties 只是插件的一种,如果需要其他插件可以支官网下载并使用。 :::

配置 loader

  1. {
  2. test: /\.js$/,
  3. use: {
  4. loader: 'babel-loader',
  5. options: {
  6. presets: ['@babel/env'], // 语法预设,有很多语法预设
  7. plugins: ['@babel/plugin-proposal-class-properties']
  8. }
  9. },
  10. exclude: /node_modules/
  11. }

官方更建议的做法是在项目目录下新建一个.babelrc的babel配置文件。

  1. {
  2. "presets": ["@babel/env"],
  3. "plugins": ["@babel/plugin-proposal-class-properties"]
  4. }

处理 generator

如果需要使用generator,无法直接使用Babel进行转换,因为会将generator转换为一个regeneratorRuntime,然后使用markwrap实现generator。但由于babel并没有内置regeneratorRuntime,所以无法直接使用。
需要安装插件:

  1. npm i @babel/plugin-transform-runtime -D

同时还需要安装运行时依赖,注意是 -S

  1. npm i @babel/runtime -S

.babelrc 中添加插件

  1. {
  2. "presets": ["@babel/env"],
  3. "plugins": [
  4. "@babel/plugin-proposal-class-properties",
  5. "@babel/plugin-transform-runtime"
  6. ]
  7. }