Webpack Configuration Guide

Time:2022-5-26

Webpack overview

webpackIs a modern JavaScript applicationStatic module bundler )

Webpack Chinese website

Webpack official website

What does webpack do

  • grammatical transformation

    • Convert less / sass to CSS
    • ES6 to Es5
    • Converting typescript to JS
  • Compression and merging of HTML / CSS / JS code (packaging)
  • Webpack can provide a development environment during development

    • Automatically open browser
    • Automatically monitor file changes
    • Automatically refresh browser
  • Projects generally need to be packaged by webpack before they go online.

Webpack module description

Webpack treats all resources as modules

  • css
  • js
  • picture
  • Font Icon

Webpack provides a modular development environment for front-end development

  • For JS files, webpack supports AMD, CMD, commonjs, ES6 modularization and other grammars
  • With webpack, we can use arbitrary modular syntax in front-end code
  • The modular syntax of nodejs can be used in browsersconst $ = require('jquery')

Webpack basic usage

  • Create a folderwebpack-demo
  • Initialize project generationpackage.json
yarn init -y
  • Install the dependency package of webpack
yarn add webpack webpack-cli -D
  • new filesrcanddistFolder,, SRC is used to provide source code, and dist is used to store packaged files
  • Created under SRCindex.jsDocument, purpose: tosrc/index.jsPackage files
  • In package The JSON file configures the packaged script
  "scripts": {
    "build": "webpack --config webpack.config.js"
  }
  • In the root directory of the project, create a filewebpack.config.js
  • Execute package command
yarn build

Configure the packaging entry of webpack

  • staywebpack.config.jsIn the file
//This is the configuration file of webpack
//Webpack runs in the node environment. Webpack can execute any node code, including modules in node.
module.exports = {
  //Default:/ src/index. js
  entry: './src/app.js'
}

Configure the packaging exit of webpack

Configure the exit of the final packaged file of webpack

//Configure webpack packaging exit
  output: {
    //Path: the directory of the package export. The default is dist. the absolute path must be specified
    path: path.join(__dirname, 'lib'),
    //Filename: the file name of the package export. The default is main js
    filename: 'bundle.js'
  }

==If you want to configure path, remember that it is an absolute path==

Configure the packaging mode of webpack

//Packaging mode development | production
  //Development: packaging will not compress the package
  //Production: packaging will compress the code
  mode: 'development'

Configuring the HTML webpack plugin

The HTML webpack plugin can help us automatically generate an HTML file in dist and automatically help us import the packaged file.

  • Install the HTML webpack plugin
yarn add html-webpack-plugin -D
  • staywebpack.config.jsMedium configuration
//1.  HTML webpack plugin import
const HtmlWebpackPlugin = require('html-webpack-plugin')

// 2. The plug-in for configuring webpack is an array
plugins: [new HtmlWebpackPlugin({
  //Template for generating HTML
  template: './src/index.html'
})

Configure CSS loader to process CSS files

Webpack can only handle JS files naturally. If you need to handle other types of files, you need to configure loader

  • Install dependent packages
yarn add css-loader style-loader -D
  • Configure loader
module: {
  rules: [
    //Rules for configuring CSS loader
    {
      //Match all CSS end file
      test: /\.css$/,
      //Handling with CSS loader and style loader
      use: ['style-loader', 'css-loader']
    }
  ]
}

==Note: the loader is loaded from right to left==

Loader less profile processing

  • Install dependent packages
yarn add less-loader less -D
  • Configure less loader
//Rules for configuring less loader
{
  //Match all Less ending file
  test: /\.less$/,
    //Handling with CSS loader and style loader
    use: ['style-loader', 'css-loader', 'less-loader']
}

Configure file loader to process pictures

  • Install dependent packages
yarn add file-loader -D
  • Configure file loader
//File loader configuration
{
  test: /\.(png|jpg|gif)$/,
  use: 'file-loader'
}

Configure URL loader to handle pictures

  • install
yarn add url-loader file-loader -D
  • Configure URL loader
{
  test: /\.(png|jpg|gif)$/,
  use: {
    loader: 'url-loader',
    options: {
      limit: 20 * 1024
    }
  }
}

Configure font icons and audio and video

//Font Icon
{
  test: /\.(eot|svg|ttf|woff)$/,
  use: {
    loader: 'url-loader',
    options: {
      limit: 20 * 1024
    }
  }
},
{
  test: /\.(mp3|mp4|ogg)$/,
  use: {
    loader: 'url-loader',
    options: {
      limit: 20 * 1024
    }
  }
}

Configure Babel loader

Babel can convert the high version of JS syntax into the low version of JS syntax to ensure the same running effect. Compatible with more browsers.

  • Install dependent packages
yarn add  babel-loader @babel/core @babel/preset-env -D
  • Configure Babel
{
  test: /\.m?js$/,
  exclude: /(node_modules|bower_components)/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: ['@babel/preset-env']
    }
  }
}

Extract CSS into a separate file

  • Install plug-ins
yarn add mini-css-extract-plugin -D
  • Plug in configuration
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

//Configure plug-ins
plugins: [
  new MiniCssExtractPlugin({
    //Specify the generated CSS file name and path
    filename: './index.css',
  })
],
  • Configure loaders for CSS and less
{
  test: /\.css$/,
  //CSS loader only enables webpack to process CSS files
  //Style loader: it can add the processed CSS code to the page
  // MiniCssExtractPlugin. loader ;  Extract CSS into a separate CSS file
  use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
  test: /\.less$/,
  use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
},

Use of webpack dev server

Webpack dev server is not used for packaging, but for starting a server. When our code changes, webpack dev server will repackage (memory) and refresh the browser to see the effect in real time

The latest version of webpack5 does not support it yet and needs to be downgraded

"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
  • Installation package
yarn add webpack-dev-server -D

#Note: if you need to use webpack dev server, you cannot use the latest version of webpack 5. Instead, you should use webpack 4
  • Configure a script
  "scripts": {
    "build": "webpack --config webpack.config.js",
    "serve": "webpack-dev-server --config webpack.config.js"
  },
  • Using dev script
yarn serve
  • Common configuration
//Configuration of devserver
  devServer: {
    //Custom port
    port: 9090,
    //Automatically open browser
    open: true
  }

Webpack processing Vue files

  • New oneApp.vuefile
<template>
  < div class = "app" > I'm the root component -- {{MSG}} -- < demo > < / demo > < / div >
</template>

<script>
export default {
  data() {
    return {
      msg: 'hello'
    }
  },
}
</script>

<style>
.app {
  background-color: red;
}
</style>
  • In main Import in JSApp.vueRoot component and render as root component
import Vue from 'vue'
import App from './App.vue'

const vm = new Vue({
  el: '#app',
  //Render app components as root components
  render: c => c(App),
  //Render app as root component
  // render: function(createElement) {
  //   return createElement(App)
  // }
})
  • An error is reported because webpack cannot process Vue files
  • Install dependent packages
yarn add [email protected] vue-template-compiler -D
  • On webpack config. Configuring Vue loader in JS
const VueLoaderPlugin = require('vue-loader/lib/plugin')

  plugins: [
    new VueLoaderPlugin()
  ],

    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]

configuration file

/*Configuration of webpack*/
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
  //Packaging entrance
  entry: './src/main.js',
  //Packing exit
  output: {
    //Configuration file
    filename: 'app.js',
    //Configure the default packaging exit path,,, which must be an absolute path
    // path: path.join(__dirname, 'lib')
  },
  //Packaging mode
  mode: 'development',
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin()
  ],
  module: {
    rules: [
      //Handling CSS
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader']
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 20 * 1024
          }
        }
      },
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  },
  devServer: {
    open: true,
    port: 8888
  }
}

My blog:http://hellozhb.top/