webpackBrief introduction:

In essence, Webpack is a static Module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles.

Can be understood as is a packaging tool, will help us all kinds of documents such as CSS, less and sass, js, ts, JPG, PNG files such as orderly packaged together.


Key Concepts:

  1. Entry: The Entry point indicates which module WebPack should use as a starting point for building its internal dependency graph.
  2. Output: The Output attribute tells WebPack where to export the bundles it creates and how to name these files./dist is the default.
  3. Loader: Loader allows Webpack to handle non-javascript files (Webpack itself can only parse JavaScript).
  4. Plugins can be used to perform a much wider range of tasks. Plug-ins range from packaging optimization and compression to redefining variables in the environment.
  5. Mode: production Mode and development Mode.

Prepare before the project begins

Install node and NPM tools, understand the basic use of NPM, CNPM, NPX and other tools.

  • Custom generate package.json file:
{
    "name":"webpack"."version":"1.0.0"
}
Copy the code
  • Or use the NPM init command to set up the environment automatically. There are many detailed configurations, such as name, version, author, etc., you can ignore them and confirm the generation.

Webpack installation:

NPM install webpack webpack-cli -g // Global installation or NPM install webpack webpack-cli -d // Local installationCopy the code

Simple compilation and packaging

Webpack. / SRC /index.js -o./dist/bundle.js --mode=development /* */ webpack./ SRC /index.js -o./dist/bundle.js --mode=production Mode changes to production mode and the code is compressed */Copy the code

Webpack can directly package JS and JSON files and output them. It can convert the es6 modular syntax into the syntax that the browser can recognize, but it can only package CSS, less and other files with the help of the loader.


Use the webpack.config.js configuration file

Webpack.config. js is a configuration file for Webpack, instructing Webpack to run and helping Webpack to run more conveniently.

  • Create a new file, webpack.config.js
  • Basic writing
const path=require('path'); Module.exports ={entry:'./src/index.js'Output :{// output file filename:'bundle.js',
    path:path.resolve(__dirname,'dist')}, the module: {/ / loader rules: [] / / detailed configuration}, plugins: [], / / plug-in mode:'development'// Mode, or use production}Copy the code

Package style resources

Common CSS resource files

  1. First you need to import CSS file resources in the entry file, for example:
// add index. CSS import to index.js'./src/index.css';
Copy the code
  1. Download the required Loader from the terminal
npm install css-loader style-loader --save-dev
Copy the code
  1. Configure the module in the webpack.config.js file
module:{
  rules:[
    {
      test:/\.css$/,
      use:['style-loader'.'css-loader']]}}Copy the code

Note that loaders in the use array are executed from right to left and from top to bottom. Style-loader can create style tags to add style resources imported from JS to the HEAD of an HTML file. Css-loader loads CSS files as CommonJS modules into JS with style strings.

  1. The configuration is packaged at the terminal using the command :webpack.

Less Resource files

The processing of less resource files is roughly the same as the CSS files above.

  1. Introduce less files in index.js
  2. Download the required Loader from the terminal
npm install css-loader style-loader less-loader --save-dev
Copy the code

Style-loader and CSS-loader can be downloaded without repetition.

  1. Configure the module in the webpack.config.js file
module:{
  rules:[
    {
      test:/\.css$/,
      use:['style-loader'.'css-loader'] {},test:/\.less$/,
      use:['style-loader'.'css-loader'.'less-loader']]}}Copy the code
  1. The configuration is packaged at the terminal using the command :webpack.

Packaging HTML files

  1. Write the original HTML file without importing other CSS and JS files.
  2. Download the htML-webpack-plugin in the terminal
NPM install html-webpack-plugin --save-dev or NPM I html-webpack-plugin -d // I is short for install, -d is short for --save-devCopy the code
  1. Do this in the webpack.config.js file
Const HtmlWebpackPlugin=require(const HtmlWebpackPlugin=require('html-webpack-plugin'); // Plugins :[new HtmlWebpackPlugin ({template:'./src/index.html'})]Copy the code

The plug-in copies the HTML file in the template, automatically importing the packaged resources.

  1. The configuration is packaged at the terminal using the command :webpack.

Package image resources

Package image resources in style resources

  1. Download the loader you need from the terminal
NPM I file-loader url-loader -d //url-loader depends on file-loader and must be used togetherCopy the code
  1. Do this in the module of the webpack.config.js file
{
  test: /\.(png|jpg|gif|svg)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        outputPath: 'images/'// Change the position of the output image file based on the output publicPath:'.. /dist/images/'// Modify the background image to import the URL pathlimit: 8 * 1024, // All image files below 8KB are base64.'[hash:8].[ext]'          // hashThe value is 7 bits, ext autocomplete file extension esModule:false; }}}Copy the code

3. After the configuration is complete, run the webpack command on the terminal to pack the package.

Package image resources in HTML files

  1. Download the loader you need from the terminal
npm i html-loader -D
Copy the code
  1. Do this in the module of the webpack.config.js file
{
  test: /\.html$/,
  use: {
    loader: 'html-loader'}}Copy the code

3. After the configuration is complete, run the webpack command on the terminal to pack the package.


Package other resources

  1. Put the resources in the directory.
  2. Import the iconfont. CSS file in index.js
  3. Add the resource file used to the HTML.
  4. Download the required file-loader from the terminal
  5. Do this in the module of the webpack.config.js file
{exclude: [/ \ | js (CSS | json | HTML) /], / / don't deal with the resource loader:'file-loader',
  options: {
    outputPath: 'media/',
    publicPath: '.. /dist/media/',
    name: '[hash:8].[ext]',}}Copy the code
  1. The configuration is packaged at the terminal using the command :webpack.

Automatic build package –devSever

Devserver can automatically compile and pack without repeating the webpack command, which is suitable for development use, but it should be noted that it only runs in memory, there is no output, that is, there is no output.

  1. Download the required resources from the terminal
npm i webpack-dev-server -D
Copy the code
  1. Activation:

Start with NPX

npx webpack-dev-server
Copy the code

Configuration Script Startup

Modify the scripts directive in package.json

"start": "webpack-dev-server"."dev": "webpack-dev-server"
Copy the code

Terminal run command: NPM start/NPM run dev

  1. Configure it in webpack.config.js
DevServer {contentBase:resolve(__dirname,'dist'),
  compress:truePort: 3000, open:true// Automatically open the browser}Copy the code

Basic configuration of the development environment

  1. Download the required Loader and plug-ins
  2. Webpack. Config. Js configuration:
const path = require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');

module.exports={
    entry:'./src/index.js',
    output:{
        filename:'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
       rules:[{
           test:/\.css$/,
           use:['style-loader'.'css-loader'] {},test:/\.less$/,
           use:['style-loader'.'css-loader'.'less-loader'] {},test:/\.(jpg|png|gif)/,
           loader:'url-loader',
           options:{
               limit:8*1024,
               name:'[hash:10].[ext]',
               esModule:false}}, {test:/\.html$/,
           loader:'html-loader'
       },
       {
           exclude:/\.(html|js|css|less|jpg|png|gif)/,
           loader:'file-loader',
           options:{
               name:'[hash:10].[ext]'
           }
       }
    ]

    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'./src/index.html'
        })
    ],
   mode:'development',
   devServer:{
    contentBase:path.resolve(__dirname,'dist'),
    compress:true,
    port:3000,
    open:true,}}Copy the code

The resources

Webpack4 tutorial from scratch

Silicon Valley 2020 latest version of Webpack5 combat tutorial (from beginner to master)