Writing is not easy, without the permission of the author is prohibited in any form of reprint!


If you think this article is good, welcome to follow, thumb up and share!

Link to the original blog post: Getting acquainted with Webpack

At the beginning of Webpack experience

What problem do you solve with Webpack

  1. modular
  2. Advanced features, development efficiency, security

    • ES6+, TypeScript, Sass, Less
  3. Monitor file changes and reflect to the browser, improve development efficiency
  4. Post-development packaging, compression, merging, tree-shaking, and other related optimizations

What is the Webpack

  • WebPCK is a static modular packaging tool for modern JS applications
  • Let’s take apart the above explanation:

    • Packaging Bundler: Webpack will help you with packaging, so it’s a packaging tool.
    • Static static: The reason for stating it this way is that we can eventually package the code into a final static resource (deployed to a static server)
    • Modular Module: Webpack supports various modular development by default, such as ES Module, CommonJS, AMD, etc
    • Modern Modern: Modern front-end development faces a variety of problems that have given rise to the emergence and growth of Webpack

Webpack and Vite

Will Webpack be replaced by Vite?

  1. After the launch of VITE, it has indeed caused a lot of reactions, and many people are optimistic about the development of VITE
  2. But there is still a long way to go before Vite replaces Webpack

    • Currently the Vue project supports the use of Vite, as well as Webpack
    • The final packaging of the Vite is still done with the help of a Rollup
  3. The core idea of Vite is not original

    • In fact, Vite’s ideas overlap with those of Snowpack, and Snowpack is more mature than it is now
    • Of course, it seems likely that Vite will surpass Snowpack
  4. Updating iterations of Webpack

    • Webpack will continue to improve itself and learn from the strengths and ideas of other tools in its development projects
    • In so many years of development, both its own advantages and the ecology are very powerful.

Thoughts on Vite

  1. Learning anything, the important thing is to learn the core idea

    • I learned JS and I didn’t learn TS from zero
    • Learning Vue, learning React does not start from 0
  2. The emergence of any tool is better to serve our development

    • Whether it is the appearance of Vite, or the advent of new tools in the future, do not have any thoughts of exclusion;
    • We need to understand deeply that tools are designed to serve us better
    • You can’t have a tool that’s going to make us less productive, and then it’s going to become very popular. It doesn’t exist

Webpack is packaged by default

  • You can package it via Webpack and then run the packaged code

    • Execute the webpack command directly from the directory

      webpack

    • Execute Webpack directly from the terminal. The native install version may differ from the project version, so define the command in package.json such as :” build”:”webpack”, which will be packaged according to the webpack version in package.json (if you have installed).
  • Create a dist folder with a main.js file in it, which will be the packaged file

    • The code in this file is compressed and uglified
    • I won’t worry about how he does it, but I’ll come back to that later when I talk about Webpack implementing the modularity principle.
    • ES6 syntax is still present in the code, such as arrow functions, const, etc. This is because by default Webpack does not know whether we need to convert the packaged file to the pre-ES5 syntax, and we need to use Babel to convert and set it later.
  • Found that it can be packaged normally, but there is a question, how does Webpack access accurately?

    • In fact, when we run Webpack, Webpack will look for SRC /index.js in the current directory as the entry
    • So, if SRC /index.js is not in the current project, an error will be reported
  • Inlets and exits can also be specified by configuration, for example (usually written in a configuration file)

    npx webpack --entry ./src/main.js --output-path ./build

Webpack configuration files

  • In general, the projects that Webpack needs to package are very complex, and we need a number of configurations to meet the requirements, and the default configuration is necessarily not available.
  • We can create a webpack.config.js file in the root directory to use as a Webpack configuration file, for example
const path = require("path");

module.exports = {
  entry: "./src/main.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "build"),
  },
};
  • Continue with the webpack command and still pack normally
  • Instead of using webpack.config.js as the file name, you can use the command to define the path and file name, for example
  • webpack --config ./wk.congfig.js

Webpack dependency graph

How exactly does Webpack package our project?

  • In fact, when Webpack works with the application, it finds the entry file by command or configuration file;
  • Starting with the entry, a dependency diagram is generated that contains all the modules needed in the application (such as JS files, CSS files, fonts, etc.)
  • It then traverse the graph structure, packaging modules one by one (using different Loaders to resolve according to different files)

Mode configures

  • The Mode configuration option tells Webpack to use the built-in optimizations in response Mode:
  • The default value is production(if nothing is set);
  • Optional values are: ‘none’ | ‘development’ | ‘production’.
  • What’s the difference between these options?

Mode configuration means more is configured

  • The green options = all the red options

Webpack core process

Reference to
Get through the core principles of Webpack

The core of this process completes two functions of content conversion and resource merging, and the realization includes three stages:

  • Initialization phase:

    1. Initialization parameters: Read from the configuration file, configuration object, Shell parameters, and combine with the default configuration to get the final parameters
    2. Create a Compiler object: Create a Compiler object with the parameters obtained in the previous step
    3. Initialize the build environment: This includes injecting built-in plug-ins, registering various module factories, initializing the RuleSet collection, loading configured plug-ins, etc
    4. Begin compilation: Executes the run method of the Compiler object
    5. Determine Entries: Find all the entry files from the entries in the configuration. Call compilition.adEntry to turn the entry files into Dependence objects
  • Construction phase:

    1. Make module: I need to call the loader to translate the module into standard JS contents. I need to call the JS interpreter to convert the contents into AST objects. I need to find out which modules the module depends on. Repeat this step until all entry dependent files have passed this step
    2. Complete module compilation: After recursively processing all accessible modules in the previous step, we get the translated content of each module and the dependency graph among them
  • Generation stage:

    1. Output resource (SEAL) : The last chance to modify the output is to assemble a Chunk of modules based on the dependencies between the entry and the module, and convert each Chunk into a separate file to be added to the output list
    2. Write to file system (EmitAssets) : After determining the output content, determine the output path and file name according to the configuration, and write the file content to the file system

The individual builds are carried out from top to bottom. The details will be discussed below. Before that, for those who are not familiar with the technical terms mentioned above, please take a look at the introduction:

  • Entry: Compiler entry, the starting point for Webpack compilation
  • CompilerCompiler: Compiler manager. After Webpack starts, a Compiler object is created, which survives until it exits
  • Compilation: Manager of a single edit process, such aswatch = trueThere is only one during the runcompiler But each time a file change triggers a recompile, a new one is createdcompilationobject
  • Dependence: Dependency object, based on which Webpack records dependencies between modules
  • Module: All resources in Webpack will exist in the form of “module” object, and all operations, translations and merges about resources are carried out in the basic unit of “module”
  • Chunk: When compiled and ready for output, Webpack willmoduleOrganized one by one according to specific ruleschunk, thesechunkSort of one-to-one with the final output
  • Loader: resource content converter, which is A converter to convert content from A to B
  • Plugin: During the Webpack build, the plugin broadcasts the corresponding events at specific times, listens for these events, and intervenes in the compilation process at specific points in time

The Webpack build process is built around these key objects. For more complete information, see the Webpack Knowledge Atlas.

Webpack and Gulp

  • The core idea of gulp is task runner

    • You can define your own set of tasks and wait for them to be executed.
    • Build streams based on file streams; / p We can use gulp’s plugin system to accomplish certain tasks.
  • The core concept of Webpack is Module Bundler PWebpack is a modular packaging tool;

    • You can use a variety of loaders to load different modules;
    • You can use a variety of plug-ins to accomplish other tasks in the Webpack packaging life cycle;
  • Advantages and disadvantages of gulp over webpack:

    • Gulp is much simpler and easier to use than Webpack and is better suited to writing automated tasks.
    • However, large projects (Vue, React, Angular) do not currently use gulp to build. For example, the default gulp does not support modularization.

Recommended articles:

  1. Get through the core principles of Webpack
  2. [source code interpretation] Webpack plug-in architecture in-depth explanation
  3. Learn more about the Webpack: module.issuer properties in ten minutes
  4. A tricky Webpack knowledge: Depth parsing of the Dependency Graph
  5. Share a few useful Webpack analysis tools
  6. Share a Webpack Knowledge Graph

Original link: Getting acquainted with Webpack

Nuggets: Front end LeBron

Zhihu: Front-end Leon

  • Continue to share technical blog posts, follow the WeChat official account 👇