The words written in the front

2020 make a wish: enter dachang! Wish to have, from the big factory is still far away! What about after reading this article? How about finishing the advanced series? Who knows! I’ll know when I see it (serious face)

  • Advanced Node.js,
  • Advanced Vue chapter,
  • Advanced HTTP,
  • Advanced performance optimization,
  • Advanced regularization and algorithms,
  • Advanced engineering chapter

The article is the author spent a lot of time to refer to the great predecessors of the article sorted out, if there is anything wrong, please do not hesitate to give advice! For all the configurations mentioned in this article, which are too long to post, here are portal Webpack 4 configuration Vue multi-page packaging best practices

What is Webpack

Webpack is a static module bundler for modern JavaScript applications. When Webpack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles. Key Concepts:

  • The entrance (entry)

This indicates which modules Webpack should use as a starting point for building its internal dependency graph, and once at the entry point, Webpack finds out which modules and libraries the entry point (directly and indirectly) depends on. Each dependency is then processed and finally exported to a file called bundles.

  • Output (output)

The Output attribute tells Webpack where to export the bundles it creates and how to name these files, with the default being./dist. Basically, the entire application structure is compiled into a folder in the output path you specify.

  • module

In Webpack, CSS, HTML, JS, static resource files and so on can all be regarded as modules. Webpack will recursively find all dependent modules from the Entry of configuration, and a module corresponds to a file.

  • Chunk

Code block: A Chunk is composed of multiple modules for code merging and splitting

  • loader

Loader enables Webpack to handle non-javascript files (Webpack itself only understands JavaScript). Loader can convert all types of files into valid modules that Webpack can handle, and then you can take advantage of Webpack’s packaging capabilities to process them. In essence, Webpack Loader converts all types of files into modules that the application’s dependency diagram (and ultimately its bundle) can reference directly

  • The plug-in (Plugins)

Plugin extends the functionality of Webpack by injecting hooks at specific points in the build process. The plugin interface is extremely powerful and gives Webpack great flexibility.

What are the features of Webpack

Modularization, compression, packaging specific functions:

  1. Set up a development environment to open the server, monitor file changes, hot update
  2. Package modules into one or more Chucks by creating dependency diagrams.
  3. Use loader to convert files such as Sass /less, images, and Vue into files in formats recognized by Webpack
  4. To be able to separate, compress and integrate resources through plug-ins

Three, WebAPCK packaging process

Detailed process:

  1. Initialization parameters: Read and merge parameters from configuration files and Shell statements to arrive at the final parameters.
  2. Start compiling: Initialize the Compiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the object’s run method to start compiling.
  3. Identify entry: Locate all entry files according to the entry in the configuration.
  4. Compiling modules: Starting from the entry file, call all configured Loader to translate the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have passed this step.
  5. Complete module compilation: After using Loader to translate all modules in Step 4, the final content of each module after translation and the dependencies between them are obtained.
  6. Output resources: Assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content.
  7. Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the file content to the file system


Simple process:

  1. Entry file starts analysis
  • Which dependency files
  • The transformation code
  1. Recursive analysis depends on code
  • Which dependency files
  • The transformation code
  1. Generate bundles that the browser can recognize for execution

Four, Webapck packaging principle

  1. ReadFileSync is used to read the entry file, and the AST abstract syntax tree is obtained via @babel/parser. With @babel/core and @babel/preset-env, the AST syntax tree is converted into appropriate code and a file object is output.

The package entry file is index.js:

import fn1 from './a.js'
fn1()
Copy the code

Dependency file A.js

const fn1 =()=>{
  console.log('1111111111')
}
export default fn1
Copy the code

Generate file objects

{filename: 'index. Js,' / / file path dependencies: '/ a. s', / / dependent files code:' \ n \ nvar _a = __webpack_require__ (/ *! ./a.js */ "./a.js"); . '// code}Copy the code

Then recurse to Dependencies, and generate:

[{filename:'index.js,' // file path dependencies:'. '\ n \ nvar _a = __webpack_require__ (/ *! / a. s * / ". / a. s ");...' / / code}, {filename: 'a. s,' / / file path dependencies: {}, code:"\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));... } ]Copy the code

Transformation format

{ 'index.js':'\n\nvar _a = __webpack_require__(/*! ./a.js */ "./a.js"); . ', 'a.js':' '\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n})); . '}Copy the code
  1. Since the generated code also includes browsers that cannot recognize the require function, a __webpack_require__ replacement of require is implemented to implement modularity, passing in an index file object via a self-executing function. The process is to run the index.js code through eval. When __webpack_require__ is encountered, the __webpack_modules__ dictionary object retrieves the a.js code and runs it through eval.

Look at the following figure in detail:

Five, common optimization means

  • MiniCssExtractPlugin: Separates and compresses the CSS
  • Happypack plugin: Happypack allows multiple threads to package resource files
  • DllPlugin: DllPlugin configates webpack.dll.conf.js to enable third-party libraries: Vue, vuex, element-UI, etc., are packaged into a bundle DLL, and a mapping file named manifest.json is generated. Finally, DllReferencePlugin is used to detect the manifest.json mapping. Filter out packages that already have mappings to avoid packing bundle.js again.
  • ParallelUglifyPlugin enables the compression output of multiple sub-processes in javascript code (TerserWebpackPlugin is used by default in WebPackage 4.0).
  • Optimization.splitchunks: Extract common files
  • Others: Exclude /include, externals, and cache-loader

Six, Webpack often meet test questions

  1. Principle of thermal renewal

Monitor file changes and refresh web pages automatically through websocket protocol (details are not yet thoroughly studied)

  1. Differences between loader and plugin

Loader: Loader is A converter that preprocesses files when importing or “loading” modules. It converts TypeScript to JavaScript, less to CSS, and simple files to files that browsers can recognize. Plugin: A plug-in is an extender designed to do other things that loader cannot do.

  1. What are the common Loaders and plugins

Loader:

  • Babel-loader: Convert ES6 to ES5
  • Less-loader: Converts less code to CSS
  • Css-loader: loads the CSS and supports features such as modularization, compression, and file import
  • Style-loader: Inserts CSS code into JavaScript and loads CSS via DOM manipulation
  • Eslint-loader: Checks JavaScript code through ESLint
  • Vue-loader: loads vue. js single file components
  • Cache-loader: can be added before some loaders with high performance overhead to cache results to disks
  • 14. file-loader: To export files to a folder and reference the output file in code by a relative URL (processing images and fonts)
  • Url-loader: similar to file-loader except that you can set a threshold. If the threshold is greater than the threshold, publicPath is returned. If the threshold is smaller than the threshold, base64 encoding is returned (processing images and fonts).

plugin:

  • CopyWebpackPlugin: Copies a single file or entire directory to the build directory
  • HtmlWebapckPlugin: Simply create HTML files for server access
  • ParallelUglifyPlugin: Multiple processes perform code compression to improve build speed
  • MiniCssExtractPlugin: Separate style files, extract CSS as separate files, support on-demand loading (alternative to extract-text-webpack-plugin)
  1. Which webapck plugins have you used to improve your productivity

This answer please refer to directory five, common optimization means

  1. Implement a simple loader

Implement a loader to replace the characters in the source code

//index.js console.log("hello"); // replaceloader.js module.exports = function(source) {// source is source.replace('hello','hello loader')}; // replaceloader.js module.exports = function(source) {// source is source.replace('hello','hello loader')};Copy the code

Use loader in the configuration file

// Const path = require('path') module: {rules: [{test: /\.js$/, use: path.resolve(__dirname,"./loader/replaceLoader.js") }] }Copy the code
  1. How to write a Webpack plugin

How it works: There are many events (run, compile, emit, etc.) broadcast during the life cycle of a Webpack run, and the Plugin can listen for these events and change the output when appropriate through the API provided by Webpack

Implement a copy Plugin

Class CopyrightWebpackPlugin {// Compiler: Webpack instance apply (compiler) {/ / before creating a resource file to the output directory emit compiler. The hooks, emit. TapAsync (" CopyrightWebpackPlugin ", (compilation, Cb) => {// assets directory output copyright.txt compilation. Assets ["copyright.txt"] = {// function() { return "hello copy"; }, // size: function() {return 20; }}; // The compilation operation is done with cb(); }); // Synchronous; Compiler.hooks.com running. Tap (" CopyrightWebpackPlugin ", compilation = > {the console. The log (" started "); }); } } module.exports = CopyrightWebpackPlugin;Copy the code

Use the CopyrightWebpackPlugin

const CopyrightWebpackPlugin = require("./plugins/copyright-webpack-plugin");
plugins: [
    new CopyrightWebpackPlugin()
  ]
Copy the code
  1. How does Webpack require find dependencies
  • Parse the relative path: Find whether there is a corresponding file or folder in the path relative to the current module. If yes, load the file directly; if yes, continue to find the package.json file under the folder

If package.json is present, search for the file based on the name of the main field in the file. If package.json is not present, search for the file index.js

  • Resolve module names: Find the node_modules folder in the current file directory, parent directory and above directory to see if there is a module with the corresponding name

  • Absolute path resolution: Directly search for files in the corresponding path

Article reference: Web Full Stack Architect issue 12

Webpack is easy to understand

How does Webpack packaging work? You will understand after reading this article!

A dozen Webpack interview questions 🔥(continue to update)

Unlock the Webpack series in depth