Why use modular packaging tools?

Modularity helps us solve the problem of disorganized code structure in complex projects, but when modularity is introduced, the project creates new problems

  • This syntax has environmental compatibility issues when implementing modularity with the ES Module, and although the latest versions of major browsers are beginning to support this new feature, there are still some environments where compatibility issues need to be addressed
  • After modularization, the project will be divided into a lot of module files, when the project runs in the browser environment, there will be frequent resource requests, affecting the project operation
  • In addition to JS files, there are many other types of resource files (HTML, CSS, images, fonts, etc.) in the project, these resources also become complex in the project, and we need to use modularity to manage them

There is a need for a tool to solve these problems and reduce the effort in the development phase beyond business coding

  • Code compiled for environment compatibility

  • Develop projects in a modular way

  • Supports different types of resource modules

Webpack, Parcel, and Rollup for major modular packaging tools

webpack

Webpack as the most mainstream modular packaging tool, can be very good to meet the above needs

  • Webpack is a Module bundler that itself solves the problem of packaging modular JavaScript code. Webpack allows you to pack the bits of code into the same JS file. For code with environment compatibility problems, we can compile and transform it through the module Loader during packaging.
  • Second, Webpack also has Code Splitting, which means that all the Code in an app should be packaged the way we want it to be. We can package the modules necessary for the initial run of the application loading process together, store the other modules separately, and asynchronously load a module when the application actually needs to work, thus achieving incremental loading.
  • Finally, for the front-end Asset Module problem, Webpack supports modular loading of any type of resource file in JavaScript.

Webpack is quick to get started

Yarn init -y // Initialize yarn add [email protected] [email protected] --dev // Import webpack and webpack-cli // webpack-cli provides the webpack command Yarn webpack // Run the pack command // default find./ SRC /index.js as the entry to./dist/main.jsCopy the code

Wepback4 and later support zero configuration file directly start packaging, using the default entry and output directory, but this way can only be js module packaging, more need to configure the packaging

Webpack will use webpack.config.js in the project root directory as the configuration file (you can also customize the configuration file path with webpack –config)

Webpack basic configuration

Webpack configuration is a custom configuration of the content of the four core concepts of the tool

  • The entrance (entry)

  • Output (output)

  • Loaders, loader)

  • The plug-in (plugins)

Entry: Tells WebPack which module to start the build with, and WebPack starts with this entry module, iterates through the encountered modules and submodules, and records the module dependencies iterated through to form a tree of content dependencies (the root node of the tree is the entry module).

module.exports = {
  entry: './src/main.js'
}
Copy the code

Output: Tell WebPack where to output the packaged results and how to name the output file names

module.exports = {
  output: {
    path: path.join(__dirname, 'dist')
  }
}
Copy the code

Loaders: Enable WebPack to handle non-javascript files (WebPack can only handle JavaScript) Loader can convert all types of files into modules that WebPack can handle and reference directly

Module. exports = {module: {rules: [{// handle CSS test: /\. CSS $/, use: ['style-loader', 'css-loader']}]}}Copy the code

Plug-ins: For performing a wider range of tasks, from packaging optimization and compression to redefining variables in the environment, can be used to handle a wide variety of tasks

Const CopyWebpackPlugin = require('copy-webpack-plugin')module.exports = {// require('copy-webpack-plugin')module.exports = { plugins: [ new CleanWebpackPlugin() ] }Copy the code

Webpack4 adds a new working mode that greatly simplifies the complexity of Webpack configuration. You can think of it as a set of preset configurations for different environments

You can set the working mode in two ways

  • The CLI argument goes to specify the packaging mode, passing –mode development to the webpack command
  • Specify mode: ‘development’ in configuration file

There are three values for this property

  • In production mode, optimization of packaging results will be automatically started.
  • In development mode, Webpack will automatically optimize the packaging speed and add some assistance needed in the debugging process to the code
  • In None mode, Webpack runs in its original state of packaging without any extra processing

How the core of WebPack works

Webpack starts from the entry module to find the dependencies, walks through the dependencies into a dependency tree, and packages the interface output

Webpack which according to the load in js code referenced in resources, rely on the dynamic process is according to the needs of js code import resources, really need not application of resources, but the code is the code to work properly, it must be to load the corresponding resources, was formed in code associated depend on the tree, to ensure that the online resources does not lack, It’s all necessary

Loader mechanism is the core of Webpack, because the code depends on resources, Webpack itself can only process JS code, other file types need Loader to load and convert file content (a function similar to translation, CSS style syntax, translated into a code string that can be executed by JS. Without Loader, WebPack is nothing more than a tool to package/merge JS code

Loading mechanism Loader

Configure the Loader in Webpack

{/ / processing image test: / \. (PNG | | GIF JPG) $/, / / small picture Data Urls with base64 loader: 'url - loader, the options: {// File-loader limit: 1024 * 2, // outputPath: 'assets' name: 'assets/[name].[hash:7].[ext]', esModule: false }},Copy the code
  1. The test property identifies the files or files that should be converted by the corresponding loader.
  2. Loader property, indicating which loader should be used for conversion
  3. The use property indicates which loaders should be used to pass an array to execute the Loader from back to forward during conversion

The process of loading resources by Webpack is a bit like a working pipeline, with multiple Loaders in turn

But the result of the pipeline must be a piece of JavaScript code

So Loader is like one of these pipes, taking the js code string from the source file or the previous Loader and returning a js code string to the next Loader or webpack

Plugin mechanism Plugin

The plug-in mechanism is another core feature in WebPack, designed to enhance WebPack automation. As we know, Loader focuses on the implementation of resource module loading, so as to achieve the packaging of the overall project

Plugin takes care of other automation tasks, such as cleaning the dist directory automatically before packaging, copying static files to the output directory, or compressing output code

Plugins have a wider range of capabilities than Loaders. The Loader only works in the module loading part, while the scope of the plug-in can touch almost every part of the WebPack work

Const {CleanWebpackPlugin} = require(' cleanwebpack-plugin ') plugins: [New CleanWebpackPlugin(), // Dist cleanup]Copy the code

Plugin is implemented by hook mechanism (similar to events). Webpack has a hook for almost every link to facilitate Plugin extension, so we can develop plug-ins by mounting different tasks on these nodes

Webpack requires that each plug-in be either a function or an object containing the Apply method. Typically, we define the plug-in as a type, and then define an Apply method within that type. To use is to build an instance of this type to use

Extensions are implemented by mounting functions in lifecycle hooks