Introduction to Webpack

Install webpack

#Query the NPM Webpack version
npm info webpack

#Current version WebPack-5
#NPM install
npm install -g webpack@5 webpack-cli@4
#Or yarn installation
yarn add webpack@5 webpack-cli@4 --dev
Copy the code

Installation position

Webpack installed in node_modules/bin of the current directory local directory uses webpack:

#Check the version
./node_modules/.bin/webpack --version
#Or use NPX to simplify operations
npx webpack --version
Copy the code

NPX may refuse to run if there is a problem with the node itself and should be handled manually using the first method

Initial setup

Run in the current project directory:

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

Package.config.js simple setup

const path = require('path');

module.exports = {
    mode: 'development'.entry: './src/index.js'.output: {
        // MD5 hash -> http caching
        filename: '[name].[contenthash].js'.path: path.resolve(__dirname, 'dist'),}};Copy the code

Package. json script setting: Resolves duplicate cache files

If the file name content hash is set, a file with different MD5 values will be generated repeatedly if the file is changed. The package.json script property can be modified to clean up duplicate files and automatically invoke Webpack at each build.

"scripts": {
   / / add the build
  "build":"rm -rf dist && npx webpack"."test": "echo "Error: no test specified" && exit 1"
},
Copy the code

Automatic HTML generation

Modify the package. The config. Js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    mode: 'development'.entry: './src/index.js'.output: {
        filename: '[name].[contenthash].js'.path: path.resolve(__dirname, 'dist'),},plugins: [new HtmlWebpackPlugin()],
};
Copy the code

Run YARN Build or NPM run build to automatically generate index.html

The introduction of CSS

  1. The installationcss-loader
npm install --save-dev css-loader
Copy the code
  1. Modify the webpack. Config. Js
module.exports = {
  module: {
    rules: [{test: /.css$/i,
        use: ["style-loader"."css-loader"],},],},};Copy the code

webpack-dev-server

Webpack.js.org/guides/deve…

  1. The installation
npm install --save-dev webpack-dev-server
Copy the code
  1. Modify the webpack. Config. Js
devServer: {
    static: {
        directory: path.join(__dirname, 'public'),},compress: true.port: 9000,},Copy the code
  1. Modify the package. The json

Add:

"start": "webpack serve --open"
Copy the code

Webpack CSS extract – CSS extract files

  1. The installation
npm install --save-dev mini-css-extract-plugin
Copy the code
  1. Modify the webpack. Config. Js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].css".chunkFilename: "[id].css",})],module: {
    rules: [{test: /.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: (resourcePath, context) = > {
                return path.relative(path.dirname(resourcePath), context) + "/"; }},},"css-loader",],},],},};Copy the code

Development and production use different webpack.config.js

  1. The first two files are required, assuming that the production mode is webpack.config.prod.js, the development mode is webpack.config.js, and the basic configuration file is webpack.config.base.js.

  2. Modify the package. The json

"scripts": {
  "build": "rm -rf dist && webpack --config webpack.config.prod.js"
},
Copy the code

Build is for production mode and start is for development mode

  1. webpack.config.js && webpack.config.base.jsBase is defined and introduced
const base = require('./webpack.config.base.js')
Copy the code
  1. webpack.config.js && webpack.config.base.jsUsing base content

. Base stands for base content

. Properties of the base content can be read

Such as:

module.exports = { ... base,mode: "production".plugins: [
    ...base.plugins,
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'.chunkFilename: '[id].[contenthash].css'.ignoreOrder: false.// Enable to remove warnings about conflicting order}),].module: {
    rules: [
      ...base.module.rules,
      {
        test: /.css$/i,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '.. / ',}},'css-loader',],}]}};Copy the code

Differences between WebPack Loader and Plugin

Webpack itself can only pack JS files, other resources (CSS, images, JSX, coffee, etc.) cannot be loaded, so the corresponding loader is required to load. Plugin extends the functionality of WebPack beyond file loading and transformation.

loader

Loader is used to load files and convert them. For example, style-loader is used to load CSS files into HTML as

plugin

Plugins, also known as plug-ins, extend the functionality of WebPack beyond resource loading. In the conversion file often can be converted to multiple files, such as HTMLWebpackPlugin to generate HTML files, *MiniCssExtractPlugin can be used to extract multiple CSS files to generate a new CSS file.

The introduction of SCSS

yarn add sass-loader dart-sass
Copy the code

Modify the webpack. Config. Js

module.exports = {
  module: {
    rules: [{test: /.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader".// Translates CSS into CommonJS
          "css-loader".// Compiles Sass to CSS
          {
              loader: "sass-loader".options: {
                  implementation: require('dart-sass'}}],},],},};Copy the code

File-loader loads image files

yarn add file-loader --dev
Copy the code

Modify the webpack. Config. Js

module.exports = {
  module: {
    rules: [{test: /.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader".// Translates CSS into CommonJS
          "css-loader".// Compiles Sass to CSS
          {
              loader: "sass-loader".options: {
                  implementation: require('dart-sass'}}],},],},};Copy the code

e.g.

A simple lazy loading module