What is webpack? The core concept of webpack

What is webpack?

In one sentence: webpack is a module bundler. The focus is on the two keywords "module" and "packaging". What is a module? Let's review the previous front-end development method. JS files are statically introduced through script tags. Since there is no strong dependency between JS files, if file 1 needs to use some methods or variables of file 2, file 1 must be loaded behind file 2. With the increase of the project, the dependencies between JS files become more and more complex, and the maintenance is more and more difficult. This dilemma drives front-end engineers to constantly explore new development models and get inspiration from the development models of back-end and app. Why not introduce the concept of "module" so that JS files can reference each other? If module 1 wants to use the functions of module 2, it only needs to explicitly refer to module 2 in module 1 without worrying about their order. Based on this idea, CommonJS and AMD specifications were created, and then required js,system.js such front-end module loading tool and node module system, until now the popular es6 module.

The introduction of module solves the problem of dependent reference between files, while packaging solves the problem of too many files. When the project scale increases and the number of modules is thousands, if the browser wants to load so many files, the speed of page loading is bound to be affected, and the bundler can package multiple associated files together, so as to greatly reduce the number of files and improve the performance of page loading. Providing modular development methods and compiling and packaging functions is the core of webpack, and many other functions are carried out around them.

 

Core concept

Module

For webpack, the module is not only a JavaScript module, but also includes any type of source files, including images, fonts and json files. Webpack supports referencing modules in the following ways:

  • ES2015 # import # method
  • CommonJs # require() method
  • AMD , define , and , require , syntax
  • @ import @ syntax in css/sass/less file
  • url(...) And < img SRC =... > Picture path in

Dependency Graph

The so-called dependency diagram is an internal logic diagram recursively generated by webpack according to the dependency relationship between each module. With this dependency diagram, webpack can package all required modules into a bundle file according to the diagram.

Entry

The starting file for drawing dependency diagrams is called entry. The default entry is/ src/index.js, or we can configure it in the configuration file. Entry can be one or multiple.

Single entry:

module.exports = {
  entry: './src/index.js'
}

perhaps

module.exports = {
  entry: {
    main: './src/index.js'
  }
};

Multiple entries and one chunk

We can also specify multiple independent files as entries, but package them into a chunk. This method is called multi main entry. We need to pass in the array of file paths:

module.exports = {
  entry: ['./src/index.js', './src/index2.js', './src/index3.js']
}

However, the flexibility and scalability of the alternative method are limited, so it is not recommended.

Multiple entries, multiple chunk s

If there are multiple entries and each entry generates a corresponding chunk, we need to pass in the object:

module.exports = {
  entry: {
    app: './src/app.js',
    admin: './src/admin.js'
  }
};

This writing method has the best flexibility and scalability, and supports merging with other partial configuration s. For example, separate the development environment from the production configuration, extract the public configuration, and merge the environment configuration and public configuration when running in different environments.

Output

With an entrance, there is an exit. As the name suggests, the export is the output packaged by webpack, and the output defines the path and file name of the output. The default output path of webpack is/ dist/main.js. Similarly, we can configure output in the configuration file:

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  }
};

Multiple entries

When there are multiple entries, one entry should correspond to one output. At this time, the output file name needs to be declared with substitutions to ensure the uniqueness of the file name. For example, use the name of the entry module:

module.exports = {
  entry: {
    app: './src/app.js',
    search: './src/search.js'
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist'
  }
}

Finally in the/ The dist app will be generated under the dist path JS and search JS two bundle files.

 

Loader

Webpack itself only supports loading js and json modules, and the idea of webpack is to let all files be referenced and loaded and generate dependency diagrams, so loader comes out. Loader enables webpack to handle other types of files (such as images, font files, xml). We can define a loader in the configuration file as follows:

webpack.config.js

module.exports = {
  module: {
    rules: [
      { 
        test: /\.txt$/, 
        use: 'raw-loader' 
      }
    ]
  }
};

test defines the file or file type to be converted, and use defines the type of loader to convert the file. This configuration is equivalent to telling webpack to convert the txt file with raw loader and then package it into a bundle when it encounters a reference to a TXT file (using require or import for reference).

There are other types of loaders, such as css loader for loading css files, file loader for loading image and font files, html loader for loading html files, and Babel loader for converting the latest JS syntax into ES5. For a complete list, please refer to webpack loaders.

 

Plugin

Plugin and loader are two confusing and vague concepts. Loader is used to convert and load specific types of files, so the execution level of loader is a single source file. The function of plugin is more powerful. Plugin can monitor the key events in the process of webpack processing and deeply integrate into the compiler of webpack. It can be said that the execution level of plugin is the whole construction process. Plugin system is the backbone of webpack. Webpack itself is also built based on plugin system. Webpack has rich built-in and external plug-ins, and allows users to customize plug-ins. These are the plug-ins officially listed.

Different from loader, when using plugin, we must first refer to the plug-in, for example:

const webpack = require('webpack'); // Used to reference webpack built-in plug-ins
const HtmlWebpackPlugin = require('html-webpack-plugin'); // External plug-ins

module.exports = {
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

 

practice

After understanding the basic concept of webpack, we can deepen our understanding through practice. Next, we use webpack to build a simple react scaffold.

 

Create project

First, create the react webpack starter project and initialize it with {npm} init}.

 

Installation dependency

Install react

npm i react react-dom

Install webpack related

npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin style-loader css-loader

After installing webpack cli, you can execute the webpack command on the command line; Webpack dev server provides a simple web server, and automatically performs the compilation operation of webpack and automatically refreshes the browser after modifying the file, eliminating repeated manual operations; HTML webpack plugin is used to automatically generate index HTML file, and in index Automatically add a reference to the bundle file in HTML; Style loader and css loader are used to load css files.

Install babel related

Because react uses es6 syntax such as class and import, we need to convert it with babel in order to improve the browser compatibility of the website.

npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader

Among them, @ babel/core is the core module of babel, which contains the core functions of babel@ babel / preset env supports the conversion of ES6 and updated js syntax, and the loaded plugin can be selected according to the compatible browser type, so as to simplify the generated code@ babel / preset react contains the plugin required by babel to transform react; babel loader is the babel loader of webpack.

 

Configure webpack

Create a new webpack under the project root directory config. JS, as follows:

webpack.config.js

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

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_module/,
        use: 'babel-loader'
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'] // Pay attention to the arrangement order. The execution order is opposite to the arrangement order
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
}

HtmlWebpackPlugin uses a custom template to generate html files. The content of the template is as follows:

./src/index.html

<!DOCTYPE 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>My React App</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

 

Configure babel

Create a new under the project root directory babelrc file to configure the two Babel presets we installed:

.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

 

Generate react application root node

./src/index

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(<App />, document.getElementById('app'));

./src/component/App.js

import React, { Component } from 'react';
import './App.css';

export default class App extends Component {
  render() {
    return (
      <div>
        my react webpack starter
      </div>
    )
  }
}

./src/components/App.css

body{
  font-size: 60px;
  font-weight: bolder;
  color: red;
  text-transform: uppercase;
}

Resource search website Encyclopedia https://www.renrenfan.com.cn Guangzhou VI design companyhttps://www.houdianzi.com

Configure package json

Finally, in package Two scripts are added to the JSON file to run the development server and package:

package.json

"scripts": {
  "start": "webpack-dev-server --mode development --open --hot",
  "build": "webpack --mode production"
}

Note that we have enabled the module hot update function (HMR) of webpack dev server to further improve our development efficiency.

Tags: Framework

Posted by jola on Mon, 02 May 2022 09:17:38 +0300