I have been using Webpack, and last time I shared the grammar reference link of Webpack configuration ES6 ~9. But for some white children, I don’t know the most basic configuration, so I just used the Spring Festival holiday to comb through the knowledge point of Webpack4. It is convenient for some people who have just entered the industry to learn, but also a summary and improvement of their own

One, the explanation of a few blind spots

  • 1, global installation and local installation

    • For the general novice there is a doubt whether I am global installation or this project installation (partial installation), personal advice, now front-end development is so fast, we use partial installation way better (using the latest technology stack).
    • We know thatjavascriptIs a weak language, there are local variables and global variables, in fact, the global installation and local installation of the nature of the function global variables and local variables are somewhat similar.
  • When installing packages — the difference between save and -d

  • We usually just use -d for packages that the development environment depends on. This will add configuration information to devDependencies in the package.json file of the project

    npm install webpack webpack-cli -D
    Copy the code
  • — Save is placed in dependencies of package.json

  • Remember to use -d only for packages that your development environment needs to use

Second,webpackThe so-called 0 configuration is used

Webpack is a configuration based front-end scaffolding that you need to configure for your plugins and loaders in a real project.

  • 1, the most basic basis of Webpack is important:

  • Plugins: configures plug-ins

  • Module: Mainly configures some loaders

  • 2. Initialize the project

  • Create a folder webpack-demo

  • Initialize to generate a package.json file

    npm init --yes
    Copy the code
  • 3, install the most basic webPack dependencies

    npm install webpack webpack-cli -D
    Copy the code
  • 4, Create a folder SRC and create an index.js file in it

  • 5. Run on the command line (ignore warnings at first)

    npx webpack
    Copy the code

  • 6. A large package of main.js will be generated in the generated dist folder. Create an index. HTML file in this folder and import main.js.

Second,webpackThe configuration of the

  • 1. Create a webpack.config.js file under the project

  • 2, can be configured

    const path = require('path');
    
    module.exports = {
      entry: ' '.// The entry for packing files
      output: {}, // The packaged export file configuration
      devServer: {}, // Development server
      module: {}, // Module configuration
      plugins: {}, // Plug-in configuration
      mode: 'development'.// ['development', 'production'
      resolve: {}, // Configuration parsing
    }
    Copy the code

3. Configure the development environment (packaged in memory)

  • 1. Installation package

    npm install webpack-dev-server -D
    Copy the code
  • 2. Configure the import and export files in webpack.config.js

    module.exports = {
      entry: './src/index.js'.// The entry for packing files
      output: {
        filename: 'build.js'.// Note that this position must be an absolute path
        path: path.join(__dirname, 'dist')},... }Copy the code
  • Configure and develop devServer

    module.exports = {
      ...
      devServer: {
        contentBase: path.join(__dirname, 'dist'),
        port: 8000.compress: true.// Automatic compression
        open: true.// Automatically open the browser}},Copy the code
  • 4. Configure commands in package.json

    . "scripts": { "dev": "webpack-dev-server", }, ...Copy the code
  • 5, debugging run command (will automatically open the browser, but there is no information display)

    npm run dev
    Copy the code
  • 6. Use htML-webpack-plugin to automatically generate HTML pages

    • 1. The installation package
    npm install html-webpack-plugin -D
    Copy the code
    • 2. Import it in webpack.config.js

      const HtmlWebpackPlugin = require('html-webpack-plugin');
      Copy the code
    • 3. Configure in plugins

      plugins: [
      	new HtmlWebpackPlugin({
      		template: './src/index.html'.title: 'webpack test'})],Copy the code
    • 4. Content about index.html

      
                
      <html lang="en">
      
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title><%=htmlWebpackPlugin.options.title%></title>
      </head>
      
      <body>
      
      </body>
      
      </html>
      Copy the code
    • 5. Please check the configuration of htML-webpack-plugin

    • 6. Run NPM run dev to directly open the browser and open the console to view the printed information

  • Create package command (add command in package.json)

    "scripts": {
    	"dev": "webpack-dev-server",
    	"build": "webpack"
    },
    Copy the code
  • 8, the use of hash values to create random generated numbers, to solve the problem of caching

    • 1. Generate random numbers for generated JS files

      output: {
      	filename: 'build.[hash].js'.// A 20-bit hash is generated by default
      	// filename: 'build.[hash:8].js' can customize how many random digits to generate
      	// Note that this position must be an absolute path
      	path: path.join(__dirname, 'dist')},Copy the code
    • 2. Generate hash values for js introduced in HTML. The hash value)

      plugins: [
      	new HtmlWebpackPlugin({
      		template: './src/index.html'.title: 'webpack test'.hash: true})],Copy the code
    • 3. Run the NPM run build command to check whether the file in dist folder has a tail (note: updating the file package will generate a new one, if the file is not changed, just multiple times will be the same).

    • 4. The effect after operation

      <script type="text/javascript" src="build.1ac0ed4b.js? 1ac0ed4bfca95df7576e"></script>	
      Copy the code
  • 9. Other common configurations of htML-webpack-plugin

    new HtmlWebpackPlugin({
      ...
      minify: {
        removeAttributeQuotes: true.// Remove double quotes
        collapseWhitespace: true.// Merge code into one line}})Copy the code

Four, clear the previouspluginUse of plugins

We delete the cached files after each packaging to ensure that they are up to date each time

  • 1, install,

    npm install clean-webpack-plugin -D
    Copy the code
  • 2. Use it in webpack.config.js

    const CleanWebpackPlugin = require('clean-webpack-plugin');
    plugins: [
    	new CleanWebpackPlugin(['./dist']),... ] .Copy the code

Five, aboutwebpackSeveral ways to import files

  • 1. Single entry file (refer to above)

  • 2, multiple entry files (can be written as an array), together packaged in an export file

    module.exports = {
      mode: 'development'.entry: [
        './src/index.js'.'./src/a.js'].output: {
        filename: 'build.[hash:8].js'.// Note that this position must be an absolute path
        path: path.join(__dirname, 'dist')}}Copy the code
  • 3, multi-entrance multi-exit multi-template mode

    • 1. Configure import files and export files

      module.exports = {
        mode: 'development'.entry: {
          index: './src/index.js'.a: './src/a.js'
        },
        output: {
          filename: '[name].[hash:8].js'.path: path.join(__dirname, 'dist')}}Copy the code
    • 2. Template configuration (specify the name of the output file)

      . plugins: [new CleanWebpackPlugin(['./dist']),
          new HtmlWebpackPlugin({
            filename: 'index.html'.// Specify the name of the packaged file
            template: './src/index.html'.title: 'webpack test 1'.hash: true.chunks: ['index']  // Specify which js file to select
          }),
          new HtmlWebpackPlugin({
            filename: 'a.html'.template: './src/index.html'.title: 'webpack test 2'.hash: true.chunks: ['a']})],}...Copy the code
    • 3. If there are many files, you can read the files

    .// Define the entry file
    let entry = {};
    const glob = require("glob");
    let HtmlPlugin = [];
    
    glob.sync('./src/*.html').forEach(item= > {
    	const filename = path.basename(item).toLowerCase();
    	const chunk = filename.replace('.html'.' ');
    	entry[chunk] = `./src/${chunk}.js`;
    	HtmlPlugin.push(
    		new HtmlWebpackPlugin({
    			filename: filename,
    			template: path.resolve(item),
    			inject: 'body'.title: 'webpack test'.chunks: [chunk],
    			hash: true.minify: {
    				removeAttributeQuotes: true.// remove quotes
    				collapseWhitespace: false.// the true code is merged into a single line}}})))module.exports = {
    	entry: entry, // Use the read entry file (note that the file must not be short [HTML and JS names must be the same])
    	output: {
    		path: path.join(__dirname, 'dist'),
    		filename: '[name].[hash:8].js'.// The name will be automatically selected based on the name above
    	},
    	devServer: {
    		contentBase: path.join(__dirname, 'dist'),
    		port: 8000.compress: false.open: true,},plugins: [
    		new CleanWebpackPlugin(), // Clear the dist folder every time you pack. HtmlPlugin, ],module: {},
    	resolve: {}}Copy the code

Vi.webpackUse of hot updates

  • 1. According to the above method, the browser will refresh if the JS code is modified, but it is similar to our manual refresh (data will be lost if there is state machine data).

  • 2. We can use a hot update plug-in that comes with Webpack

  • 3. Way of use

    • 1. Configure the configuration in webpack.config.js

      const webpack = require('webpack'); . plugins: [new webpack.HotModuleReplacementPlugin(), // Every time the code is modified, it is refreshed automatically in the development environment. ] .Copy the code
    • 2. Add it to the main entry index.js file

      if (module.hot) {
        module.hot.accept();
      }
      Copy the code