background

One of the things I knew early on that Babel was going to help us do was convert the high ES syntax to the low ES syntax to make sure it worked on the low ES syntax.

But I never knew how to manipulate it, only that it took a bunch of configuration and webpack to do it (and I even thought I had to use WebPack to do it).

Integration (basically copying documents)

In fact, if you use Baidu search, integrated things have a variety of ES version of the dependency, configuration files js, RC, JSON files, a mess of everything.

It’s historical. But it’s 2021, so let’s just stick to what the website says.

1. Download the dependency package

npm install --save-dev @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill
Copy the code

Of course, I personally think that if you don’t need to be compatible with IE, you don’t need to download Polyfill

2. Add dependent files

Create a configuration file named babel.config.json in the root directory of your project (v7.8.0 or later required) and copy the following into this file:

{ "presets": [ [ "@babel/env", { "targets": { "edge": "17", "firefox": "60", "chrome": "67", "safari": "11.1"}, "useBuiltIns" : "usage", "corejs" : "3.6.5,"}}]]Copy the code
  • The list of browsers above is for example only. Depending on which browser you want to support.

If @babel/core is later than 7.8.0, you should use babel.config.js

3. You can compile directly

For example, convert all files under SRC to the lib folder

npx babel src --out-dir lib
Copy the code

In other words, if you are doing some simple re-packaging of some libraries for internal use, Babel is probably all you need and webPack is not required.

Don’t want to integrate, just one or two files, just want to quickly get converted code to solve the problem temporarily

Babel’s online tools are worth using

Cooperate with webpack

It also works with WebPack

In addition to the ones added above

babel-loader

npm i babel-loader -D
Copy the code

Add corresponding parsing rules to webpack.config.js

module: {
  rules: [
    {
      test: /\.m?js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }
  ]
}
Copy the code

Of course, if you need more optimized configuration, you can see the documentation for babel-Loader