Understand the basic configuration of WebPack

1.1 Initializing the WebPack project

Create a new directory and initialize it

npm init
Copy the code

Installing dependency packages

npm i -D webpack webpack-cli
Copy the code

Create a new folder SRC, write an entry file main.js and test the configuration command in package.json

"build":"webpack src/main.js"
Copy the code

perform

npm run build
Copy the code

The packaging succeeds if a dist folder is generated

1.2 Adding Configurations

In order to generate different JS each time we need to do the following configuration

module.exports = {
    // Omit other configurations
    output: {
      filename: '[name].[hash:8].js'.// The packed dynamic file name
      path: path.resolve(__dirname,'.. /dist')  // The packaged directory}}Copy the code

So how do you get packaged JS to load into HTML? For single-entry files, you can perform the following configuration

First of all:

npm i -D html-webpack-plugin
Copy the code

Then: create a new “build” folder named “public” and create a new “index.html” folder

Specific configuration file:

// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    mode:'development'.// Development mode
    entry: path.resolve(__dirname,'.. /src/main.js'),    // Import file
    output: {
      filename: '[name].[hash:8].js'.// The packaged file name
      path: path.resolve(__dirname,'.. /dist')  // The packaged directory
    },
    plugins: [new HtmlWebpackPlugin({
        template:path.resolve(__dirname,'.. /public/index.html')]}})Copy the code

So let’s talk about how to configure multiple portals.

1.3 Configuring multi-entry Files

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    mode:'development'.// Development mode
    entry: {
      main:path.resolve(__dirname,'.. /src/main.js'),
      header:path.resolve(__dirname,'.. /src/header.js')},output: {
      filename: '[name].[hash:8].js'.// The packaged file name
      path: path.resolve(__dirname,'.. /dist')  // The packaged directory
    },
    plugins: [new HtmlWebpackPlugin({
        template:path.resolve(__dirname,'.. /public/index.html'),
        filename:'index.html'.chunks: ['main'] // The module name corresponding to the entry file
      }),
      new HtmlWebpackPlugin({
        template:path.resolve(__dirname,'.. /public/header.html'),
        filename:'header.html'.chunks: ['header'] // The module name corresponding to the entry file]}}),Copy the code

After executing build, different HTML and js will be generated, so try it out.

1.4 Clearing files generated during the last package

Based on the previous step, you will find that your dist folder is regenerated every time you pack. Over time, your dist folder will have a lot of useless junk files, so we introduced the clean-webpack-plugin plugin

Configuration is as follows

const {CleanWebpackPlugin} = require('clean-webpack-plugin')
module.exports = {
    / /... Omit other configurations
    plugins: [new CleanWebpackPlugin()]
}
Copy the code

1.5 deal with CSS

How do we reference CSS first, first we need to import our CSS in the entry JS

import './assets/index.css'
Copy the code

And then I’ll introduce the plug-in

npm i -D style-loader css-loader
npm i -D less less-loader
Copy the code

Configure in webpack.config.js

module.exports = {
    module: {rules:[
        {
          test:/\.css$/,
          use:['style-loader'.'css-loader'] // Parse principles from right to left
        },
        {
          test:/\.less$/,
          use:['style-loader'.'css-loader'.'less-loader'] // Parse principles from right to left}}}]Copy the code

Now we can see the loaded CSS

1.5.1 Adding the Browser Prefix
npm i -D postcss-loader autoprefixer  
Copy the code

Configuration is as follows

// webpack.config.js
module.exports = {
    module: {rules:[
            {
                test:/\.less$/,
                use:['style-loader'.'css-loader'.'postcss-loader'.'less-loader'] // Parse principles from right to left}}}]Copy the code

Autoprefixer is then introduced to make it work in two different ways, depending on the Node.js version

Create a postcss.config.js file in the postcss.config.js directory

module.exports = {
    plugins: [require('autoprefixer')]  // Just reference the plugin
}
Copy the code

Method 2: Configure it directly in webpack.config.js

// webpack.config.js
module.exports = {
    module: {rules: [{test:/\.less$/,
            use:['style-loader'.'css-loader', {loader:'postcss-loader'.options: {plugins: [require('autoprefixer')]}},'less-loader']]}}}Copy the code
1.5.2 split CSS
npm i -D mini-css-extract-plugin
Copy the code

configuration

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
  module: {
    rules: [{test: /\.less$/,
        use: [
           MiniCssExtractPlugin.loader,
          'css-loader'.'less-loader']],}},plugins: [
    new MiniCssExtractPlugin({
        filename: "[name].[hash].css".chunkFilename: "[id].css",}})]Copy the code
1.5.3 Splitting Multiple CSS
npm i -D extract-text-webpack-plugin@next
Copy the code

configuration

const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
let indexLess = new ExtractTextWebpackPlugin('index.less');
let indexCss = new ExtractTextWebpackPlugin('index.css');
module.exports = {
    module: {rules:[
        {
          test:/\.css$/,
          use: indexCss.extract({
            use: ['css-loader']})}, {test:/\.less$/,
          use: indexLess.extract({
            use: ['css-loader'.'less-loader']})}]},plugins:[
      indexLess,
      indexCss
    ]
}
Copy the code

1.6 Escape THE JS file

npm i -D babel-loader @babel/preset-env @babel/core
Copy the code

configuration

// webpack.config.js
module.exports = {
    // Omit other configurations...
    module: {rules:[
          {
            test:/\.js$/,
            use:{
              loader:'babel-loader'.options: {presets: ['@babel/preset-env']}},exclude:/node_modules/}}},]Copy the code

The above plugins cannot convert the new API, so the following configuration must be added

npm i @babel/polyfill
Copy the code

configuration

// webpack.config.js
const path = require('path')
module.exports = {
    entry: ["@babel/polyfill",path.resolve(__dirname,'.. /src/index.js')].// Import file
}
Copy the code

1.7 Introduction to Other Plug-ins

When most of our work is done by people, it is important to format code using Prettier

1.7.1 prettier

The steps are as follows

yarn add prettier --dev --exact
Copy the code

In the root directory of the project, create the.prettierrc.js file.

module.exports = {
  printWidth: 120.// The maximum length per line is 80 by default
  tabWidth: 2.// A TAB represents several Spaces
  useTabs: false.// Whether to use TAB for indentation
  semi: false.// Declaration followed by a semicolon
  singleQuote: true.// Use single quotes
  trailingComma: 'none'.endOfLine: 'auto'
}
Copy the code

Adding script Commands

{
  "script": {
    "prettier": "prettier --write ./src/**.{js,css}"}}Copy the code
1.7.2 Using ESLint to review JS code

The steps are as follows

1. Install ESLint

yarn add eslint -D
Copy the code

There are two ways to create.eslintrc files:

Create.eslintrc.js file to execute script commands automatically generated

Method 1: Create the.eslintrc.js configuration file to install dependencies

yarn add eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node -D
Copy the code

Create the.eslintrc.js file in the root directory of the project

module.exports = {
  env: {
    browser: true.es2020: true
  },
  extends: ['standard'].parserOptions: {
    ecmaVersion: 12.sourceType: 'module'
  },
  rules: {}}Copy the code

After installing ESLint, run NPX eslint –init to automatically generate.eslintrc configuration files.

Eslint-plugin-prettier Eslint-config-prettier To prettier code, install the following:

Eslint-config-prettier: When prettier is used alongside Linter, the configuration of plugins conflicts. To solve this problem, we use the eslint-config-prettier plug-in, which shuts off part of ESLint configuration so that prettier’s configuration overwrites ESLint’s.

Eslint-plugin-prettier: EsLint checks projects using the rule where Prettier is used.

Run the following command to install the plugin and configuration

yarn add eslint-plugin-prettier eslint-config-prettier eslint-config-recommended -D
Copy the code

4. Adjust. Eslintrc. Js file We can use the prettier with the configuration of the plugin: prettier/it, it will do three things:

Open eslint – plugin – prettier

Setting prettier/prettier rule to “error” inherits eslint-config-prettier configuration

So we inherit ESLint in engineering (ESLint: it) and Prettier (plugin: Prettier/it) configuration, namely in the list extends, Add ‘eslint: it’ and ‘plugin: prettier/it. .eslintrc.js

module.exports = {
  env: {
    browser: true.es2020: true
  },
  extends: ['eslint:recommended'.'plugin:prettier/recommended'].parserOptions: {
    ecmaVersion: 12.sourceType: 'module'}}Copy the code
1.7.3 Other Plug-ins

1. Add ESlint-Loader: js code is automatically reviewed during development and packaging.

2. Add postCSS-loader: allows us to use a new generation of CSS syntax in our projects.

3. Add stylelint: Reviews the CSS syntax in the project as a command line.

4. Added pre-commit Hook: mandatory code check before code submission.

5. Add Commitizen: Standardize the format of Git log messages.

6. Add commitLint: Force a review of the log format submitted by Git before committing code.

7. Add standard-version: Changelog.md is automatically generated. Establish a relationship between work order and log.