1, WebPack manual build 15 steps

1, the installation

 npm install -g webpack webpack-cli
Copy the code

2. Package and compile HTML files

NPM install -d clean-webpack-plugin To clean dist file NPM install -d HTML -webpack-plugin to generate index.htmlCopy the code

3, hot update

 npm install -D webpack-dev-server
Copy the code

4, Babel compilation

  npm install babel-loader @babel/core @babel/preset-env @babel/plugin-transform-runtime -D
  npm install -S @babel/runtime
  npm install -S @babel/plugin-syntax-dynamic-import
Copy the code

5, CSS

npm install -D css-loader style-loader sass npm install -D node-sass sass-loader less npm install -D less less-loader Postcss: the prefix is automatically added. The CSS is modular. NPM install -d postcss-loader NPM install -d autoprefixerCopy the code

6. Enable hot replacement of modules

Hot :true Install cross-env add an environment variable, CNPM install cross-env -s environment separation, need to install webpack-merge CNPM install webpack-merge -dCopy the code

7. Environment variables

Get the value of the variable through the Webpack.definePluginCopy the code

8, development environment configuration view source code

 devtool:'cheap-module-eval-source-map'
Copy the code

9, CSS extraction

 cnpm install -D mini-css-extract-plugin 
Copy the code

10, image font resources processing

CNPM install -d file-loader url-loader Html-witming-loader CNPM install -d HTml-withimg-loaderCopy the code

Extract common code

Configuration: splitChunks in OptimizationCopy the code

12. JS and CSS compression

   cnpm install -D babili-webpack-plugin 
   cnpm install -D optimize-css-assets-webpack-plugin
Copy the code

13. Change relative paths of static resources to absolute paths

CNPM install -d copy-webpack-plugin csS-loader Start modularizationCopy the code

14, Mock

   cnpm install -D mockjs
   cnpm install -D express
   cnpm install -D nodemon 
Copy the code

2, complete WebPack manual build code

1, webpack. Base. Config

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ENV_NODE = process.env.ENV_NODE
console.log(process.env.MOCK)
module.exports = {
  entry: {
    index: './src/index.js'.about: './src/about.js',},output: {
    filename: ENV_NODE === 'production' ? '[name].[contenthash:7].js' : '[name].[hash:7].js'.chunkFilename: ENV_NODE === 'production' ? '[name].[chunkhash:7].js' : '[name].[hash:7].js'.path: path.resolve(__dirname, "dist"),
    publicPath: '/',},resolve: {
    alias: { // Configure the alias
      The '@': path.resolve(__dirname, 'src'),},extensions: ['.js'.'.css'.'.scss'.'.less']},module: {
    rules: [{test: /\.(jsx|js)$/,
        use: {
          loader: "babel-loader",},exclude: /node_modules/}, {test: /\.(css|scss|sass)$/,
        use: [  / / MiniCssExtractPlgin. Replace style - loader loader in order to extract the CSS
          ENV_NODE === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
          {
            loader: 'css-loader'.options: {modules: {
                localIdentName: '[path][name]-[local]-[hash:base64:5]'}}},'postcss-loader'.'sass-loader'] {},test: /\.less$/,
        use: [
            ENV_NODE === 'production' ? MiniCssExtractPlugin.loader : 'style-loader',
            {
              loader: 'css-loader'.options: {modules: {localIdentName: '[path][name]-[local]-[hash:base64:5]'}}},'postcss-loader'.'less-loader'] {},test: /\.(png|svg|jpg|gif)$/,
        use: [{
          loader: 'url-loader'.options: {
            limit: 1024 * 10.// Convert images of 10K or less to Base64 and wrap them in JS
            name: '[name].[hash:7].[ext]'.// The file name of the package
            outputPath: 'images/'.esModule: false}}}, {test: /\.(woff|woff2|eot|ttf|otf)$/,
        use:[{
          loader: 'url-loader'.options: {
            limit: 1024 * 5.// If the value is less than 10K, wrap it in JS
            name: '[name].[hash:7].[ext]'.outputPath: 'font/'}}}, {test: /\.(htm|html)$/,
        use: [{
          loader: 'html-withimg-loader'}]}],},plugins: [
    new CleanWebpackPlugin(), // Clean up the dist folder
    new HtmlWebpackPlugin({
      // Generate HTML automatically
      template: "./index.html".//
      filename: "index.html".// Where is the script tag, default true, inside the body, head, false
      inject: true.hash: true./ / today
      minify: {
        minifyJS: true.minifyCSS: true.removeComments: true.removeEmptyAttributes: true.collapseBooleanAttributes: true.removeScriptTypeAttributes: true.removeStyleLinkTypeAttributes: true.collapseInlineTagWhitespace: true.collapseWhitespace: true,},chunks: ['styles'.'vendor'.'common'.'manifest'.'index'],}).new HtmlWebpackPlugin({
      // Generate HTML automatically
      template: "./about.html".//
      filename: "about.html".// Where is the script tag, default true, inside the body, head, false
      inject: true.hash: true./ / today
      minify: {
        minifyJS: true.minifyCSS: true.removeComments: true.removeEmptyAttributes: true.collapseBooleanAttributes: true.removeScriptTypeAttributes: true.removeStyleLinkTypeAttributes: true.collapseInlineTagWhitespace: true.collapseWhitespace: true,},chunks: ['styles'.'vendor'.'common'.'manifest'.'about'],}).new CopyWebpackPlugin({
      patterns: [{from: path.join(__dirname, '/src/public'), to: 'public'}]})],// Extract the common code
  optimization: {
    splitChunks: {
      chunks: 'all'.Initial, all, async(async module, default)
      minSize: 30000.// Limit the minimum size of extracted files before compression: the default is 30,000
      maxSize: 0.// The maximum value is 0 by default
      minChunks: 1.// Indicates the number of times it was introduced. The default is 1
      maxAsyncRequests: 5.// The default maximum number of asynchronous requests is 5
      maxInitialRequests: 3.// The maximum number of initial loads defaults to 3
      automaticNameDelimiter: '~'.// The separator of the automatically generated name of the extracted file, default ~
      name: true.// The name of the extracted file. True indicates the name of the automatically generated file. Default is true
      // All the parameters are default values, so you can leave them alone.
      // cachGroups is the key to the configuration, which can override all splitChunks.
      // Set the cache component to extract chunks that meet different rules
      cacheGroups: {
       // Pack all the CSS files into one and set the weight to the highest
       sytles: {
         name: 'styles'.test: /\.(css|scss|sass|less)$/,
         chunks: 'all'.enforce: true.// Use the upper layer configuration minSize configuration
         priority: 20.// The higher the priority, the higher the priority
       },
       // Third-party libraries are packaged separately
       vendor: {
         test: /node_modules/,
         chunks: 'initial'.name:'vendor'.priority: 10.enforce:true
       },
       // Extract all modules that have been imported more than once as common
       common: {
         name: 'common'.chunks: 'initial'.priority: 2.minChunks: 2.enforce:true}}},runtimeChunk: { // Extract the manifest to manage the interaction between modules
      name: 'manifest'}}};Copy the code

2, webpack. Dev. Config

const { merge } = require('webpack-merge')
const path = require('path')
const baseConfig = require('./webpack.base.config')
const webpack = require("webpack");
// const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const devConfig = {
  mode: "development".devServer: {
    contentBase: path.join(__dirname, 'dist'), // The root directory of the website
    host: "localhost".port: "9527".compress: true.// Set server compression
    hot: true  // Enable hot replacement of modules
  },
  devtool: 'cheap-module-eval-source-map'.plugins: [
    new webpack.NamedModulesPlugin(), // When HMR is enabled, using this plugin displays the relative path of the module,
    new webpack.HotModuleReplacementPlugin(), / / open HMR
    new webpack.DefinePlugin({ // Get the packaged environment variables from the plug-in
      "ENV_MOCK": process.env.MOCK
    }),
    / / CSS
    // new MiniCssExtractPlugin({
    // filename: 'css/[name].[hash:7].css',
    // chunkFilename: 'css/[id].[name].[hash:7].css'
    // })]};module.exports = merge(baseConfig, devConfig)
Copy the code

3, webpack.prod.config.js

const { merge } = require('webpack-merge')
const baseConfig = require('./webpack.base.config')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const BabiliPlugin = require('babili-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const proConfig = {
  mode: 'production'.plugins: [
    / / CSS
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:7].css'.chunkFilename: 'css/[name].[chunkhash:7].css'})].optimization: {minimizer: [
      new BabiliPlugin(), // A babel-based compression tool that supports some ES6 features instead of UglifyJS
      new OptimizeCSSAssetsPlugin() / / compress CSS]}}module.exports = merge(baseConfig, proConfig)
Copy the code

3, webpack summary

The running process of Webpack is a serial process, with the following processes executing sequentially from start to finish

  1. Initialization parameters: read and merge parameters from the configuration file and command line, initialize the configuration parameters of this build, and get the final parameters;
  2. Start compiling:Initialize the parameters obtained in the previous stepCompilerObject to load all of the configuration filesplugin, the run method of the execution object starts compiling;
  3. Determine entry:According to the configurationentryFind all entry files and recursively iterate through all entry files;
  4. Compiling modules:Starting from the entry file, invoke all configuredloaderCompile the module, find out which modules the module depends on, and repeat this step until all the entry dependent files have been processed by this step.
  5. Output resources:All files have been compiled and transformed, namely the final output of resources, including the resources to be output, code blocksChunkAnd so on.

Summary: Summarize the essence in one sentence:

Webpack is a tool for packaging modular JS, which can be converted by loader and extended by plugin.Copy the code