1. Introduction

All this time, my understanding of WebPack was in the early stages, with no complex configuration, and no real project experience. Interview questions can only go back to the use of scaffolding… I found a course some time ago. This is a note of the course

2. What is Webpack

Description of the website:

Essentially, WebPack is a static Module Bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a dependency graph that contains every module the application needs, and then packages all of those modules into one or more static resources (bundles).

Put it into your own words:

  • Webpack is a resource building tool on the front end, a static module packager;
  • In webpack point of view, the front of all the resource files (js/json/CSS/less SCSS/img /…). They’re all modules;
  • Webpack generates a dependency diagram based on the resource dependencies, which are then packaged into corresponding static resource bundles.

3. Core concepts

3.1. Before concepts: The general process of WebPack packaging

  • Starting from Entry Entry, analyze and build an internal dependency graph to find out which modules and libraries are directly and indirectly dependent on Entry.
  • Start processing each of the dependencies found:
    • Webpack can directly handle JS, JSON files;
    • Webpack can’t handle files (CSS, less, SCSS, PNG, JPG…) Use loader to process;
    • Use plugins for optimization, compression, etc.
    • After processing, they are exported to files, which we call bundles;
  • After processing the bundles, WebPack will find the target folder according to the configuration of the export output, create the target file, and write these bundles to the target file.

3.2. Five core concepts

Entry – Entry

An Entry is the starting point module (a module is a file) for WebPack analysis to build an internal dependency graph.

// webpack.config.js:
module.exports = {
  entry: './path/to/my/entry/file.js'
};
Copy the code

Exports – the Output

The output property tells WebPack where to output the bundles it creates and how to name them. The default value is./dist.

// webpack.config.js:
const path = require('path');
module.exports = {
  entry: './path/to/my/entry/file.js'.output: {
    // Output path:
    // --dirname: nodeJs variable, representing the absolute path to the current file
    // resolve: nodeJs' path 'method used to concatenate the absolute path
    path: path.resolve(__dirname, 'dist'),
    // Output file name
    filename: 'my-first-webpack.bundle.js'}};Copy the code

Loader

  • Loader lets WebPack handle files that are not JavaScript (WebPack itself only understands JavaScript);
  • Loader can convert all types of files into valid modules that WebPack can handle.

Loader use:

  • Need to download first;
  • Don’t need torequrie.
// webpack.config.js:
const { resolve } = require('path');
const config = {
  output: {
    filename: 'my-first-webpack.bundle.js'.path: resolve(__dirname, 'dist')},module: {
    rules: [
      // Different types of files must be configured with different rules for processing
      {
        test: /\.css$/.// What files to match
        // Loaders are executed from bottom to top, right to left (last in, first out)
        use: [
          'style-loader'.'css-loader']}]};module.exports = config;
Copy the code

Plug-in – Plugins

Plugins can be used to perform a wider range of tasks than loaders. Plug-ins range from packaging, optimization and compression, to redefining variables in the environment…

Use of plugin:

  • Need to download first;
  • Still need torequrie.
// webpack.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install via NPM
const webpack = require('webpack'); // To access the built-in plug-in
const config = {
  module: {
    rules: [{test: /\.txt$/, use: 'raw-loader'}},plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'}})];module.exports = config;
Copy the code

Mode – Mode

  • Mode instructs WebPack to use the configuration for the corresponding Mode;
  • mode: 'development' | 'production';
  • Production and development environments compile ES6 modularity into modularity that can be recognized by browsing;
  • The production environment has one more compressed JS code than the development environment;
options describe The characteristics of
development willDefinePluginIn theprocess.env.NODE_ENVIs set todevelopment. To enable theNamedChunksPluginandNamedModulesPlugin. An environment where code can be debugged locally
production willDefinePluginIn theprocess.env.NODE_ENVIs set toproduction. To enable theFlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin SideEffectsFlagPlugin and TerserPlugin. An environment that allows code optimization to come online
// webpack.config.js:
module.exports = {
  mode: 'production'
};
Copy the code

4. Use webpack

Webpack really needs to be done to make it more profound

My webpack version: “webpack” : “^ 5.44.0”, “webpack – cli” : “^ 4.7.2”; (The full code is here, in these two folders: WebPack First Experience and WebPack First Experience 2)

4.1. Do not use configuration files

If loader and plugins are not involved, you can use the command line packaging.

Step 1: Prepare

You need to install WebPack and webpack-CLI.

npm i webpack webpack-cli -D
Copy the code

Step 2: Write code

The code is here

Directory structure:

├── SRC │ ├─ index.js │ ├─ test.htmCopy the code

Code:

// 1. src/index.js
import data from './test.json';
console.log(data);
function add(x, y) {
  return x + y;
}
add(1.2)
console.log(add(1.2))

// 2. src/test.json
{
  "testJson": "test json"
}
Copy the code

Step 3: Pack

Enter the following command at the project root directory:

  • Development environment:
    • Command:webpack ./src/index.js -o ./build_dev/ --mode=development;
    • What it means: WebPack starts with./ SRC /index.js and outputs to./build_dev/main.js. The overall packaging environment is development environment.
  • Production environment:
    • Command:webpack ./src/index.js -o ./build_prod/ --mode=production;
    • What it means: WebPack starts with./ SRC /index.js and outputs to./build_prod/main.js.

4.2. Using the Configuration file

Step 1: Prepare

  • As with no configuration files, you need to install WebPack and webpack-CLI.
  • You also need to install the loader and plugins used.
NPM I webpack webpack-cli -d // Download loader and plugins NPM I xxx-loader xxx-plugin -dCopy the code

Step 2: Write code

You need to write a configuration file called webpack.config.js in the root directory of your project.

Directory structure:

2 ├── SRC │ ├─ index.js │ ├─ test.json ├── webpack.configCopy the code

Code:

// 1. src/index.js
import data from './test.json';
console.log(data);
function add(x, y) {
  return x + y;
}
add(1.2)
console.log(add(1.2))

// 2. src/test.json
{
  "testJson": "test json"
}

// 3. webpack.config.js
const { resolve } = require('path'); // 
module.exports = {
  entry: './src/index.js'.output: {
    filename: 'built.js'.path: resolve(__dirname, 'build')},module: {
    rules: [{test: /\.css$/,
        use: [
          'style-loader'.'css-loader']]}},plugins: [].mode: 'development'
}
Copy the code

Step 3: Pack

Enter the command webpack into the project root directory. Once packaged, the console will also display some package-related information for those interested to take a closer look.