Configuration of Babel in Webpack

In daily development, if you use ES6, ES7, and other advanced syntax in your project, the browser won’t recognize it. This is where you need to use Babel to convert the syntax to ES5 syntax for browser recognition.

Babel’s website is www.babeljs.cn/

Instructions for installing Babel

References: www.cnblogs.com/guolao/arch…

Official website installation instructions: www.babeljs.cn/setup#insta…

Babel provides a variety of installation methods for components, and here we choose webPack installation.

After selecting WebPack, the installation method of the corresponding component will be displayed. Let’s install it according to the method provided on the official website.

But first, initialize a WebPack build file structure.

Build the file structure for WebPack

Initialize the package.json file

Package. json uses the stored record NPM to install the relevant package version. Run the following command to initialize:

npm init -y
Copy the code

Execute as follows:

Install webpack

Install the Webpack tool into your local project:

npm i -D webpack webpack-cli
Copy the code

Execute as follows:

The output package file is set up using webPack’s configuration file

The purpose of this build is just to verify that the advanced JS syntax will compile properly after Babel is installed, so I won’t write anything in index.html.

Create and write the configuration file webpack.config.js in the project root directory

const path = require('path');

// This configuration file, which starts as a JS file, exposes a configuration object through module operations in Node
module.exports = {
    // In the configuration file, you need to specify the entry and exit manually
    entry: path.join(__dirname, './src/main.js'),// entry, indicating which file to pack with WebPack
    output: { // Output file related configuration
        path: path.join(__dirname, './dist'), // Specify the directory to export the packaged files to
        filename: 'bundle.js' // This is the name of the output file}};Copy the code

Normally, the webpack command would do the packing now, but I installed Webpack into my local project above, so I still need to script NPM to execute the internal command.

Execute local Webpack execution commands in package.json configuration

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."dev": "webpack"
  },
Copy the code

Now that this is configured, you can use the NPM run script name to execute it as follows:

npm run dev
Copy the code

You can see that the bundle.js compressed file has been successfully edited and packaged.

writemain.jsPrint the information to set index.html to reference the bundle.js script

First write a printed message in main.js as follows:

console.log("hello world");
Copy the code

Then add bundle.js to index.html as follows:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script src=".. /dist/bundle.js"></script>

</body>
</html>

Copy the code

At this point, execute NPM run dev to package a new bundle.js and open index.html to see if it can print the following information:

So it’s time to install Babel and use a more advanced syntax to see if it compiles successfully.

Write the ES6 syntax in main.js and view the printed information

Before installing Babe to convert ES6\ES7 to less than ES5, I tested it and found that the ES6 syntax works in Chrome, but in Internet Explorer it does not:

The main.js code looks like this:

// ES5
console.log("hello world es5");

// ES6
class Bar {
    doStuff() {
        console.log('stuff bar'); }}var b = new Bar();
b.doStuff(); // "stuff"

// ES6
class Foo {
    static classMethod() {
        return 'hello static foo'; }}console.log(Foo.classMethod()); // 'hello'

Copy the code

Now run the NPM run dev package to compile bundle.js.

Start by viewing index. HTML in Chrome and view the printed information as follows:

Chrome supports ES6 syntax by default.

Then open Internet Explorer and view the index.html. The printed information is as follows:

Note Internet Explorer does not support es6 syntax by default.

So, let’s start installing and configuring Babel and see if Internet Explorer supports it later.

Install Babel

Install Babel into a local project:

cnpm i -D babel-loader @babel/core
Copy the code

Execute as follows:

To convert es6 code, install the Babel plug-in:

cnpm i -D @babel/preset-env @babel/polyfill
Copy the code

Execute as follows:

Create the Babel configuration file in the root directory. Babelrc:

{
  "presets": ["@babel/preset-env"]}Copy the code

Configure webpack.config.js to set the rules for using Babel

module: {
  rules: [{test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}}]Copy the code

Check the advanced syntax again in Internet Explorer

NPM run dev = NPM run dev = NPM run dev = NPM run dev

Prevention of global pollution

Use @babel/ plugin-transform-Runtime to prevent global contamination if you are writing third-party libraries or frameworks.

Installation:

npm i -D @babel/plugin-transform-runtime
npm i -S @babel/runtime @babel/runtime-corejs2
Copy the code

Note: Use -d –save-dev to install it into the test development environment, and -s –save to install it into the production environment dependencies.

Run as follows:

Add Babel configuration:

{
  "presets": ["@babel/preset-env"]."plugins": [["@babel/plugin-transform-runtime",
      {
        "corejs": 2."helpers": true."regenerator": true."useESModules": false}]]}"corejs": 2.// Set this to 2 because the version installed above is
Copy the code

For more exciting original Devops articles, please come to my official account: Devops Community: