Refer to the link: www.cnblogs.com/skychx/p/we…

Complete links ➡️ webpack can be confusing

 

Js, utils.js, common.js and index.css. The directory structure is as follows:

SRC / ├─ index.css ├─ index.html # ├─ index.js ├─ common.js ├── uss.jsCopy the code

Index.css write a simple style:

body {
    background-color: red;
}
Copy the code

Utils. Js file to write a square utility function:

export function square(x) {
    return x * x;
}
Copy the code

Common. js file to write a log utility function:

module.exports = {
  log: (msg) => {
    console.log('hello ', msg)
  }
}
Copy the code

Make some simple changes to the index.js file, introducing the CSS file and common.js:

import './index.css';
const { log } = require('./common');


log('webpack');
Copy the code

The configuration of Webpack is as follows:

{ entry: { index: ".. /src/index.js", utils: '.. / SRC /utils.js',}, output: {filename: "[name].bundle.js", // output: {index.js and utils.js}, module: {rules: [{test: /.css$/, use: [MiniCssExtractPlugin. Loader, / / to create a link tags' CSS - loader, / / CSS - loader is responsible for parsing the CSS code, processing of the dependence of CSS],},]} plugins: New MiniCssExtractPlugin({filename: 'index.bundle. CSS '// output CSS file named index.css}),]}Copy the code

Let’s run WebPack and see the result:

 

CSS and common.js are introduced in index.js, and the bundle generated index.bundle. CSS and index.bundle.js belong to chunk 0, utils.js because they are packaged separately. The utils.bundle.js it generates belongs to Chunk 1.

A little convoluted? I made a picture that I’m sure you’ll understand:

 

Look at this graph and it makes sense:

  1. For a piece of code with the same logic, when we write down one file after another, whether they are ESM or commonJS or AMD, they are modules;
  2. When the module source file we wrote is sent to Webpack for packaging, Webpack will generate a chunk file according to the file reference relationship, and Webpack will perform some operations on this chunk file.
  3. After processing the chunk files, WebPack finally outputs the bundle file, which contains the loaded and compiled final source file, so it can be run directly in the browser.

In general, a chunk corresponds to a bundle, such as in the figure above, utils.js -> chunks -> utils.bundle.js; There are exceptions, such as in the example above, where I use the MiniCssExtractPlugin to pull out the index.bundle. CSS file from chunks 0.

 

Conclusion:

Module, chunk, and bundle are the same logical code with three names in different transformation scenarios:

We write modules directly, webpack processes chunks, and finally generate bundles that the browser can run directly.