Webpack -- common processing of CSS, html and js code

 

preface

This paper summarizes the common processing methods of css, js and html code in webpack. The learning notes are for reference only.

text

1. css style file processing

(1) extract css as a separate file

Based on the previous study of webpack, we know that after packaging, webpack puts the css style file in js, which leads to file confusion. In this step, we need to package the css style file into a separate file, that is, extract it from js.

First, you need a basic weback environment, and then install the MiniCssExtractPlugin. The command is as follows:

npm  i mini-css-extract-plugin -D

Then add the following configuration in webpack.config.js:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

// to configure loader
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          // "style-loader", // Create a style label and put the style into
          //this loader replace style-loader ,The function is to extract js Medium css Into a separate document
          MiniCssExtractPlugin.loader,
          "css-loader", // take css Entire file to js in
        ],
      },
    ],
  },
  // to configure plugin
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
    new MiniCssExtractPlugin({
      // Rename the output file
      filename:"css/build.css"
    }),
  ],

When you execute the webpack package command, you will find that the CSS file is separately packaged in the main.css file in the CSS directory.

(2) css compatibility processing

When handling css compatibility, you need to use postcss. You need to execute the following command to download the corresponding loader

    npm i postcss-loader postcss-preset-env -D

Then configure the following in webpack.config.js

const { resolve } = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// set up node Environment variables:
process.env.NODE_ENV="development"
module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "build.js",
    path: resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          // "style-loader", // Create a style label and put the style into
          //this loader replace style-loader ,The function is to extract js Medium css Into a separate document
          MiniCssExtractPlugin.loader,
          "css-loader", // take css Entire file to js in
          /* CSS Compatibility processing: postcss = = > postcss loader postcss preset env
          Help postcss access the configuration in the browserlist in package.json, and load the specified css compatible style through the configuration
          "browserlist":{
            // Development environment = = "set node environment variable: process.env.NODE_ENV="development"
              "development":[
                "last 1 chrome version",
                "last 1 firefox version",
                "last 1 safari version"
              ],
              // The production environment defaults to the production environment
              "production":[
                ">0.2%",
                "not dead",
                "not op_mini all"
              ]
            }*/
          // use loader Default configuration for
          // post-loader
          // modify loader to configure
          {
            loader:"postcss-loader",
            options:{
              ident:"postcss",
              plugins:()=>{
                require("postcss-preset-env")
              }
            }
          }
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
    new MiniCssExtractPlugin({
      // Rename the output file
      filename:"css/build.css"
    }),
  ],
  mode: "development",
};

If the following error is reported here, it is because this version of postcss loader does not support writing in the webpack.config.js file. We can change the writing method

  Create a new postcss.config.js file in the root directory, add the following code, and then annotate the options object in postcss loader

module.exports={
    ident:"postcss",
    plugins:()=>{
        require("postcss-preset-env")
      }
}

Execute the packaging command webpack and find that the css code after packaging will have compatibility processing such as prefix

(3) css code compression

css code compression is often used in the production environment. Here, you need to use the optimize css assert webpack plugin plug-in. Install it with the following command

    npm i optimize-css-assets-webpack-plugin -D

Then add the following configuration in webpack.config.js

const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin")// introduce
    // Add in configuration
  plugins: [
    // css Code compression plug-in
    new OptimizeCssAssetsWebpackPlugin()
  ],

Execute the webpack command and find that the css code is compressed into one line.

2. JavaScript code processing

(1) syntax check of JS code

In order to standardize your JS code, you often use the syntax check eslint loader. This loader depends on the eslint library and only checks the source code. It will not check the code specification in webpack.config.js, but you need to set the syntax check rules. airbnb is commonly used as the check rule. Download dependencies first:

    npm i eslint-loader eslint eslint-config-airbnb-base eslint-plugin-import -D

Add the configuration eslintConfig in package.json:

  "eslintConfig": {
    "extends": "airbnb-base"
  }

Configure the loader in webpack.config.js

     {
        test: /\.js$/,
        exclude: /node_modules/, // exclude node_modules
        loader: "eslint-loader",
        options: {
          fix: true,// Automatic repair eslint error
        },
      },

When you execute the webpack packaging command, you will find that our js code has been standardized.

(2) JS compatibility processing

Some syntax of ES6 is not supported in some browsers, and compatibility processing is required. You need to use the Babel loader and @ babel/core core core libraries. First, download the dependencies

    npm i babel-loader @babel/core  -D

1. Basic js compatibility processing: @ Babel / preset env is required, and installation depends on

    npm i @babel/preset-env  -D

Then configure the loader in webpack.config.js

      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /node_modules/, // exclude node_modules
        options: {
          // Presets: indication babel What compatibility processing
          presets: ["@babel/presets-env"],
        },
      },

Problem: it is not compatible with advanced syntax such as promise.

2. All js compatible processing @ babel/polyfill

    npm i  @babel/polyfill  -D

Then import it into the portal file

    import "@babel/polyfill"

Problem: all js compatibility processing codes will be introduced, and the code volume is large after packaging

3. Load compatibility processing core JS on demand

    npm i core-js -D

Then configure the loader in webpack.config.js, where you need to comment on all compatibility processing in step 2.

      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: /node_modules/, // exclude node_modules
        options: {
          // Presets: indication babel What compatibility processing
          presets: [
            "@babel/presets-env",
            {
              useBuiltins: "usage", // Load on demand
              corejs: {
                version: 3, // appoint corejs edition
              },
              targets: {
                // Specify which browsers are compatible with
                chorme: "60",
                firefox: "60",
                ie: "9",
                safiri: "10",
                edge:"17",
              },
            },
          ],
        },
      },

(3) compression of JS code

The code compression webpack of JS will execute itself. You only need to set the mode to production mode. The UglifyJsPlugin of webpack itself will automatically perform the compression task.

Configure mode in webpack.cofig.js

      mode: "production",

3. html code compression

Just configure HtmlWebpackPlugin.

Configure HtmlWebpackPlugin in webpack.cofig.js.

    new HtmlWebpackPlugin({
      template: "./index.html",
      minify: {
        // Remove spaces
        collapseWhitespace: true,
        // Remove comment
        removeComments: true,
      },
    }),

Write at the end

The above is the whole content of this article. I hope to bring some help and progress to readers. If it is convenient, pay attention. Xiaobai's growth path will continue to update some common problems and technical points in his work.

 

Posted on Thu, 02 Dec 2021 15:59:42 -0500 by TLawrence