Previous article: Front end Automation testing

Here comes another serial! This time we will be divided into four articles to introduce how to build a WebPack development environment from 0, understand its internal mechanism and principle, so that we can more accurately grasp and use Webpack, the following start our start:

1. What is Webpack?

Webpack is a static module bundler for modern JavaScript applications. When WebPack processes an application, it recursively builds a dependency graph containing every module the application needs, All of these modules are then packaged into one or more bundles

Using Webpack as a front-end build tool:

  • Code conversion: TypeScript to JavaScript, SCSS to CSS, etc.
  • File optimization: compress JavaScript, CSS, HTML code, compress and merge images, etc.
  • Code segmentation: extract the common code of multiple pages, extract the code that does not need to execute part of the first screen and load it asynchronously;
  • Module merge: in a modular project, there will be many modules and files. You need to build functions to merge modules into a single file.
  • Automatic refresh: monitor local source code changes, automatically rebuild, refresh the browser;
  • Code verification: verify code compliance and pass unit tests before it is submitted to the repository;
  • Automatic release: After updating the code, automatically build the online release code and transfer it to the release system.

There are two cores in the WebPack application:

    1. Modular converter, is used to convert the original content of the module into new content as required, and can load non-JS modules;
    1. extensionsInject extension logic at specific points in the Webpack build process to change the build result or do what you want.

2. Initialize the project

├ ─ ─ the SRC# source directory│ ├─ ├─ ├─ ├─ ├.jsCopy the code

Write a – module. Js

module.exports = 'hello';
Copy the code

Write index. Js

let a = require('./a-module');
console.log(a);
Copy the code

Here we introduce the CommonJS module, which doesn’t work on browsers by default, and we want to pack it with WebPack!

3. Webpack is a quick start

3.1 installation

npm init -y
npm install webpack webpack-cli --save-dev
Copy the code

Webpack supports 0 configuration by default to configure scripts

"scripts": {
  "build": "webpack"
}
Copy the code

When NPM run build is executed, the default webpack command in node_modules/. Bin will be called, and the internal webpack-CLI will be called to resolve user parameters for packaging. The default entry file is SRC /index.js.

NPX webpack can also be used here, NPX is the.bin executable provided by NPM after version 5.2

We find that we have generated the dist directory, which is the result of the final package. Main.js can be referenced directly in HTML, and we are prompted that the default mode is production.

3.2 webpack. Config. Js

We usually don’t use 0 configuration when packaging, webpack will look for the webpack.config.js or webpackfile.js file in the current directory by default when packaging.

Package through configuration files:

const path = require('path');
module.exports = {
    entry:'./src/index.js'.output: {filename:'bundle.js'.// Package the resulting file
        path:path.resolve(__dirname,'dist')// Package to the dist directory}}Copy the code

3.3 Configuring the packaged Mode

We need to provide the mode attribute at packaging time to distinguish between the development environment and the production environment to split the configuration file.

├─ Build │ ├─ ├─ ├.dev.js │ ├─ ├─ ├.prod.jsCopy the code

We can do this by specifying different files

Configure scripts scripts:

"scripts": {
  "build": "webpack --config ./build/webpack.prod",
  "dev": "webpack --config ./build/webpack.dev"
}
Copy the code

The config parameter specifies which configuration file to use for packaging.

Using the env parameter

"scripts": {
    "build": "webpack --env.production --config ./build/webpack.base",
    "dev": "webpack --env.development --config ./build/webpack.base"
}
Copy the code

Modify the default export function of the webpack.base file to pass environment variables to the function’s parameters.

module.exports = (env) = >{
    console.log(env); // { development: true }
}
Copy the code

Merge configuration files

We can determine whether the current environment is a development environment to load different configurations. Here we need to do configuration merge install webpack-merge:

npm install webpack-merge --save-dev
Copy the code

Webpack. Dev configuration

module.exports = {
    mode:'development'
}
Copy the code

Webpack. Prod configuration

module.exports = {
    mode:'production'
}
Copy the code

Webpack. Base configuration

const path = require('path');
const merge = require('webpack-merge');
// Development environment
const dev = require('./webpack.dev');
// Production environment
const prod = require('./webpack.prod');
const base = { 
    // Basic configuration
    entry:'./src/index.js'.output: {filename:'bundle.js'.path:path.resolve(__dirname,'.. /dist')}}module.exports = (env) = >{
    if(env.development){
        return merge(base,dev);
    }else{
        returnmerge(base,prod); }}Copy the code

In future development, we will put the common logic in base, and the configuration in development and production will also be stored separately!

4.webpack-dev-server

Configure the development server so that the implementation can be packaged in memory and automatically start the service.

npm install webpack-dev-server --save-dev
Copy the code
"scripts": {
    "build": "webpack --env.production --config ./build/webpack.base",
    "dev": "webpack-dev-server --env.development --config ./build/webpack.base"
}
Copy the code

Start the development environment by executing NPM run dev:

By default, the service is started in the current root directory

Configure the configuration of the development service

const path = require('path')
module.exports = {
    mode:'development'.devServer: {// Change the static file directory location
        contentBase:path.resolve(__dirname,'.. /dist'),
        compress:true./ / open gzip
        port:3000.// Change the port number}}Copy the code

5. Package the Html plug-in

5.1 Single-entry Packaging

Automatically generate HTML and import packaged files

Edit the webpack.base file

const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins:[
    new HtmlWebpackPlugin({
        filename:'index.html'.// The name of the packaged file
        template:path.resolve(__dirname,'.. /public/index.html'),
        hash:true.// Add a hash stamp to the end of the reference resource
        minify:{
            removeAttributeQuotes:true // Delete attribute double quotes}})]Copy the code

5.2 Multi-entry Packing

Generate multiple JS files according to different entries and import them into different HTML:

└─ SRC ├── entry-1.js ├── entry-2.jsCopy the code

Multiple entries You need to configure multiple entries

entry:{
    jquery: ['jquery']./ / packaging jquery
    entry1:path.resolve(__dirname,'.. /src/entry-1.js'),
    entry2:path.resolve(__dirname,'.. /src/entry-2.js')},output: {filename:'[name].js'.path:path.resolve(__dirname,'.. /dist')},Copy the code

Generate multiple HTML files

new HtmlWebpackPlugin({
    filename:'index.html'.template:path.resolve(__dirname,'.. /public/template.html'),
    hash:true.minify: {removeAttributeQuotes:true
    },
    chunks: ['jquery'.'entry1'].// Chunk to be imported includes jquery and Entry
}),
new HtmlWebpackPlugin({
    filename:'login.html'.template:path.resolve(__dirname,'.. /public/template.html'),
    hash:true.minify: {removeAttributeQuotes:true
    },
    inject:false.// Inject false indicates that js files are not injected
    chunksSortMode:'manual'.// Manually configure the code block order
    chunks:['entry2'.'jquery']})Copy the code

The above method is not very elegant. The HtmlPlugin should generate the HTML file dynamically each time you add it manually, like this:

let htmlPlugins = [
  {
    entry: "entry1".html: "index.html"
  },
  {
    entry: "entry2".html: "login.html"
  }
].map(
  item= >
    new HtmlWebpackPlugin({
      filename: item.html,
      template: path.resolve(__dirname, ".. /public/template.html"),
      hash: true.minify: {
        removeAttributeQuotes: true
      },
      chunks: ["jquery", item.entry]
    })
);
plugins: [...htmlPlugins]
Copy the code

6. Empty the packing results

You can manually clean a folder using the clean-webpack-plugin:

The installation

npm install --save-dev clean-webpack-plugin
Copy the code
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
new CleanWebpackPlugin({
    // Clear matched paths
    cleanOnceBeforeBuildPatterns: [path.resolve('xxxx/*'),'* * / *'],})Copy the code

This clears the specified directory, and we can see that the basic use of webpack plugins is new Plugin and placed in plugins.

7. Summary

Do you now have an initial impression or more ideas about how to use WebPack? Are the swords of the gods about to break? Stay tuned for the next webPack configuration!