primers

Why write this article? Because today’s nuggets morning paper had an article about how to get started with Webpack, after reading it, I realized that I really need to learn about Webpack, so I have this article. My knowledge of WebPack is limited to vue-CLI, which is of course off-the-shelf, and I’ve never used it myself. However, as I grow up, I must understand these and then simply build a webpack packaging tool of my own.

  1. Webpack (1) – Understanding of core concepts
  2. Webpack (2) – Configuration details
  3. .

Try a webpack

When I learn something new for the first time, I always understand three questions first:

  1. What it is;
  2. What it can do;
  3. What does it mean roughly at each step.

concept

This is defined in the Webpack document:

In essence, Webpack is a static Module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles.

It is not difficult to understand its meaning with the homepage picture of its official website: All files, such as JavaScript, CSS, SASS, IMG/PNG, are modules in the eyes of Webpack. Modules are combined and packaged by configuring Webpack. After processing by Webpack, the final output will be static resources that the browser can use.

The core concept

Now that you have a basic understanding of what Webpack is and what it does, it’s time to figure out how to use it. Following the Webpack documentation, it requires us to understand a few core concepts before it can be used:

  • Entry portal
  • Output Output result
  • Loader module converter
  • The Module Module
  • The Chunk of code block
  • The Plugin plug-in

Entry

Entry is the entry to the configuration module that instructs Webpack to perform the first step of the build. You can configure the Entry property in a configuration file to specify one or more entry points

There are three types of entry: string, array, and object.

  • String: “./ SRC /entry” File path of the entry module. It can be a relative path
  • Array: [“./ SRC /entry1”, “./ SRC /entry2”] Specifies the file path of the entry module. It can be a relative path. Unlike strings, arrays pack multiple files into a single file
  • object{ a: ‘./src/entry-a’, b: [‘./src/entry-b1’, ‘./app/entry-b2’]}Configure multiple entrances, one for each entranceChunk

Output

Output configures how to output the final desired code. Output is an object that contains a list of configuration items.

  • Filename Specifies the name of the output file.
  • Path Absolute path of the destination output directory. It must be absolute.

The module, the Loader

How does the module configuration handle modules

Configure the Loader

The module. Rules array in the configuration configures a set of rules that tell Webpack which Loader to use to load and convert which files it encounters.

  • useProperty should be an array of Loader names,LoaderThe order of execution is from back to front;
  • eachLoaderCan passURL querystringFor examplecss-loader? minimizeIn theminimizetellcss-loaderWant to openCSSCompression.

Plugins

Plugins are used to extend Webpack functionality, and a variety of plugins allow Webpack to do almost anything build-related.

Configure the Plugin

Plugin configuration is simple. Plugins take an array of items, each of which is an instance of the Plugin to be used, and the parameters needed by the Plugin are passed in through the constructor.

Of course, the difficulty of using Plugin is to understand the configuration items provided by Plugin itself, not how to plug Plugin into Webpack.

Try gayHub for a feature that Webpack doesn’t have! Oh no, Github try your luck!

Chunk

Chunk, code block, is a packaged output file.

Webpack assigns a name to each Chunk and can distinguish the filename of the output based on the Chunk name.

filename: '[name].js'
Copy the code

An entry file with the default chunkname main. In addition to the built-in variable name, there are other variables associated with Chunk:

  • id ChunkUnique identifier of, starting from 0
  • name ChunkThe name of the
  • hash ChunkIs uniquely identified byHash
  • chunkhash ChunkThe content ofHash

Simply configure a Webpack

Now that you know the basics, just drive, cough, cough, and get to work.

// ./webpack.config.js

module.exports = {
    mode: 'development',
    entry:{
        app1: './src/index.js',
        app2: './src/main.js'
    },
    output: {
        path: __dirname + '/dist',
        filename: '[hash][name].js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                loader: 'style-loader! css-loader'
            },
            {
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }
};
// ./src/index.css
html {
    background: # 333;
    color: #fff;
}
// ./src/index.js
import './index.css'
const sleep = async time => await new Promise( resolve => {
    setTimeout(() => {console.log(' wait${time}s`)
        returnresolve }, time*1000) } ) sleep(5) console.log(`Success! `) // ./src/main.js const sleep = async time => await new Promise( resolve => {setTimeout(() => {console.log(' wait${time}s`)
        return resolve
    }, time*1000)
} )
sleep(2)


// .babelrc
{
  "presets": [
    "es2015"."stage-0"]."plugins": [["transform-runtime", {
      "polyfill": false."regenerator": true
    }]
  ]
}

// package.json
{
  "name": "webpack-demo"."version": "1.0.0"."description": ""."main": "webpack.config.js"."dependencies": {
    "babel-core": "^ 6.26.3"."babel-polyfill": "^ 6.26.0"."babel-preset-es2015": "^ 6.24.1"."babel-preset-stage-0": "^ 6.24.1"."css-loader": "^ 0.28.11"."style-loader": "^ 0.21.0"."webpack": "^ 4.8.3"."webpack-cli": "^ 2.1.3"
  },
  "devDependencies": {
    "babel-loader": "^" 7.1.4."babel-plugin-transform-runtime": "^ 6.23.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Aditya"."license": "ISC"
}

Copy the code

The code above was the first Webpack demo I wrote and it was really easy to get started, so I quickly configured a webpack that could package CSS, ES6, async/await according to the documentation.

Some of these dependencies are installed as follows

// NPM i-d is short for NPM install --save-dev NPM i-d webpack webapck-cli NPM i-d css-loader style-loader NPM i-d babel-loader babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-plugin-transform-runtimeCopy the code

CSS – loader and style – loader

Problems encountered during configuration: CSS code is packaged but does not work.

At the beginning of the Loader configuration, I only wrote CSS-loader, because today read the blog only write CSS-loader, but they did not write any CSS style =. =

So using the search engine in hand, the process should look like this:

When Webpack encounters a file ending in.css, it uses csS-loader to read the CSS file, which is then handed over to style-loader to inject the CSS content into JavaScript.

The style-loader works like this: it stores CSS content as JavaScript strings, and dynamically inserts style tags into the head tag through DOM manipulation during JavaScript execution.

Let’s talk about Babel

Those of you who know ES6 should know that some browsers and Node.js already support ES6, but because they don’t fully support all ES6 standards, they are afraid to fully use ES6 in their development. In general, we need to convert code written in ES6 to ES5 code that already supports well. This involves two things:

  1. New ES6 syntax is implemented in ES5, for example, ES6 class syntax is implemented in ES5 Prototype.
  2. Polyfill the new API, such as the corresponding Polyfill when using the new FETCH API, to make the low-end browser work.

Babel can do both of these things easily. Babel is a JavaScript compiler that can convert ES6 code into ES5 code, allowing you to use the latest language features without worrying about compatibility, and flexibly extend as needed through a plug-in mechanism.

During Babel compilation, the configuration is read from the.babelrc file in the project root directory. .babelrc is a JSON file with the following contents:

{
  "presets": [
    "es2015"."stage-0"]."plugins": [["transform-runtime", {
      "polyfill": false."regenerator": true}}]]Copy the code

babel-loader

Babel-loader is required. Access Babel via loader in Webpack to complete transcoding

Babel – preset – es2015 and Babel – preset – stage – 0

The presets attribute tells Babel which new syntax features are being used in the source code being converted. A single preset supports a set of new syntax features, and multiple presets can be stacked. Presets are collections of Plugins, each of which performs the task of converting a new syntax.

  1. Has been writtenECMAScriptFeatures in the standard, since new features have been added to the standard every year, can be subdivided into:
  • Es2015 includes new features added in 2015;
  • Es2016 includes new features added in 2016;
  • Es2017 includes new features added in 2017;
  • Es2017 includes new features added in 2017;
  • Env contains all the latest features in the current ECMAScript standard.
  1. Features proposed by the community but not yet written into the ECMAScript standard fall into the following four categories:
  • Stage0 is just a nice radical idea, there is a Babel plugin that supports these features, but it is not certain that they will be made standard;
  • Stage1 features worthy of inclusion in the standard;
  • Stage2 This feature specification has been drafted and will be included in the standard;
  • Stage3 This feature specification has been finalized and major browser vendors and the Node.js community have started implementing it.
  • Stage4 will be added to the standard over the next year.

3. In order to support the syntax for some specific application scenarios, it has nothing to do with ECMAScript standard. For example, babel-preset- React is used to support JSX syntax in react development.

babel-plugin-transform-runtime

The Plugin property tells Bable which plug-ins to use, and plug-ins control how the code is transformed.

Babel-plugin-transform-runtime is an add-on to reduce redundant code. But why do we use it? This is mainly due to the use of ES 7 async functions.

Because the Runtime compiler plug-in does three things:

  • When you usegenerators/asyncFunction is automatically introducedbabel-runtime/regenerator
  • Automatically is introduced intobabel-runtime/core-jsAnd mapES 6Static methods and built-in plug-ins.
  • Remove inlineBabel helperAnd use modulesbabel-runtime/helpersInstead.

Transform-runtime: transform-runtime

For other specific uses of Babel, consult the official Babel documentation

Write in the last

This is the end of the first step of learning Webpack. There are too many materials to read and too many things to learn, so I can’t remember them in a moment. It’s paving the way. Welcome the boss to point out the shortcomings.