1. Concept of engineering

It is to improve front-end development efficiency through various tools and technologies. Including development, compilation, deployment and other stages.

2. Modular ideas, CommonJS, ESModule

  • Early modularity, namespaces, self-executing functions,

CommonJS this is the module specification that node.js follows,

A file represents a module. Each file has a separate scope, exporting members through module.exports and loading modules through the require function. Modules are loaded synchronously, so the operation efficiency is low

Front-end module, asynchronous loading module specification for browser environment

  • The AMD() specification, Requirejs, dependency preloading, and all require are executed ahead of time
  • The CMD specification, seaJS, does not perform loading until require is encountered in the callback function after downloading
  • Esmodule is a standard developed in ECMAScript 2015(ES6). It is exported and imported by export and import.

3. Principle and construction process of Webpack

Webpack is a static module packaging tool for modern JS applications. It starts from the entry file, edits the module, compiles recursively according to dependencies, and builds a dependency tree. Generate one or more file bundles.

What problem was solved

  • Module packaging: You can package files from different modules together and ensure that they are referenced correctly and executed in an orderly manner. Make sure the project structure is clear and readable.
  • Compile compatibility: polyfill code and convert.less,.vue,.jsx files. It has code compilation capabilities to convert the code we wrote during development into code that can run in most browser environments
  • Ability expansion: Plugin mechanism of Webpack can further realize a series of functions such as on-demand loading, code compression and so on, helping us to further improve the degree of automation, engineering efficiency and quality of packaged output.

Build Process (Brief)

  • Initialization: reads and merges configuration, loads plugin, instantiates complier
  • Compilation: Starting from the entry file, the loader corresponding to the module is called for compilation for each module, and then the module that the module depends on is compiled recursively according to the dependency relationship.
  • Output: The compiled modules are grouped into chunks, and the chunks are converted into bundles. Output to the file list according to the configuration

Slightly detailed version

The running flow of Webpack is a sequential process, from start to finish:

  • Initialization: reads and merges the configuration to instantiate complier, loads the plugin configuration plug-in, and executes the object’s run method to start compiling
  • Compilation: Starting from the entry file, the loader corresponding to the module is called for compilation for each module, and then the module that the module depends on is compiled recursively according to the dependency relationship. Get the final translated content of each module and the dependencies between them
  • Output: The compiled modules are grouped into chunks according to the dependencies between the entry and modules, and the chunks are converted into bundles. Determine the output path and file name according to the configuration, and output the output to the file list

4. The essence and difference between Loader and Plugin

loader

  • Loader: Essentially a function that processes the imported resources and then places a javascript module around the function
  • Why loader is needed, because WebPack treats everything as a module and itself only recognizes JS and JSON files. Therefore, loader needs to convert files of other types into files that WePack can parse.

plugin

  • Webpack broadcasts many events during its running life cycle, and by listening for these events, plugin can perform its own plug-in tasks at a specific stage, thus realizing the desired function to change the output result.

The difference between

  • Loader parses files and plugin extends functions
  • Loader is used in module.rules as module parsing rules, type array. Plugins are configured separately in plugins. The types of plugins are arrays. Each item is an instance of plugin.
// Get webpack configuration options, write loader's first set of routines
cosnt { getOptions } = require('loader-utils')

module.exports = function(content, map, meta){
  const options = getOptions(this) || {}

  cosnt code = JSON.stringify(content);
  const esModule  = typeofoptions.esModule ! = ='undefined' ? options.esModule : true
  // Return the content
  return `${esModule ? 'export default' : 'module.exports ='} ${json}; `;
}
Copy the code

5. Webpack optimization

The development of optimization

  • 1. Preload removes js files that do not need to be loaded in advance, such as maps
  • 2. Delete prefetch. The Prefetch link consumes bandwidth.
  • 3. Babel-plugin-dynamic-import-node is used to eliminate the need for lazy loading of hot updates in the development environment

Compiler optimization

  • Use older versions of Webpack and Node.js
  • Multi-process/multi-instance builds: HappyPack(no longer maintained), Thread-loader
  • External and DLL use CDN for modules that are not frequently changed, or package them into DLL packages to reduce compilation time.
  • dllPlugin,DllReferencePlugin
  • Include and exclude to restrict loader compilation returns
  • It’s all in the load on demand framework
  • Make full use of cache to improve secondary build speed: babel-loader enables cache

Volume optimization

  • SplitChunks are subcontracted
  • Minimize entry chunk
new CommonsChunkPlugin({
  name: 'manifest'.minChunks: Infinity
});
Copy the code

6. Babel is what

Babel is a Javascript Transpiler.

use

There are three main things we use Babel for

  • Translate exNext, typescript, Flow, and other jS supported by the target environment
  • Some special-purpose code conversions. Such as automatic burial point
  • Static analysis of code

How did Babel convert ES6 to ES5

Babel’s translation is divided into three stages: parsing, transforming, and generating.

  • Parse: Convert source code to an abstract syntax tree (AST) using Parser

Babel divides ES6 + (for ES6 and above) into a syntax layer and an API layer: syntax layer: let, const, class, arrow functions, etc. These need to be translated at build time. Will be translated as var function… API layer: Promise, includes, Map, etc. These are methods that are added to global or Object, Array, etc prototypes and can be redefined in the appropriate ES5 manner

  • Transfrom: Traverses the AST, calling various Transform plug-ins to add, delete, and change the AST
  • Generate: Prints the transformed AST as object code and generates sourcemap

7.vite

Is a browser based on the native ES module import development server, in the development environment, the use of the browser to parse import, on the server side according to the need to compile and return, completely skipped the concept of packaging, the server is ready to use. At the same time, Vue files are not only supported, but also support hot update, and the speed of hot update does not slow down with the increase of modules. Use Rollup packaging in a production environment

  • 1. Build tools such as Webpack and Rollup pack modules into JS bundles that can be read by browsers in advance during local development and debugging.
  • 2. Optimization methods such as lazy loading of routes, but lazy loading does not mean lazy construction, Webpack still needs to build the modules used by your asynchronous routes in advance.
    1. Vite takes advantage of the browser’s native ES Module support to start a server locally, and when the browser reads the HTML file, it sends a request for the Module to the server only when it executes an import.
  • 4. Through some internal mechanisms, the vite server will parse the module into js files that can be executed by the browser and return them to the browser.
  • 5. This ensures that the browser will only request and parse loads when the module is actually used, maximizing load on demand
  • 6. Dependency precompilation, in fact, Vite 2.0 uses esbuild to pre-build the detected dependencies before starting the development server for the user, all packaged into a traditional JS bundle
<div id="app"></div>
<script type="module">
  import { createApp } from 'vue';
  import Main from './Main.vue';
  createApp(Main).mount('#app');
</script>
Copy the code

8. Hot Module Replacement (HMR) Is also called Hot Replacement

When you make changes to the code and save it, WebPack repackages the code and sends the new module to the browser, which replaces the old module with the new module and can update the application without refreshing the browser.

  • The core of HMR is that the client pulls the updated file from the server. Chunk Diff, to be exact,
  • In fact, WDS(Webpack-dev-server) maintains a Websocket to communicate with the browser.
  • When a local resource changes, WDS pushes the update to the browser with a build-time hash, allowing the browser to compare it to the last resource
  • After comparing the differences, the client makes an Ajax request to WDS to get the changed content (list of files, hash), i.e. request update.json,
  • The client can then use this information to make a JSONP request to WDS for incremental updates to the chunk, i.e. request update.js. The updated JS is stored in memory

other

What plug-ins have you used to improve your productivity while developing with WebPack?

  • Webpack-dashboard: A more user-friendly presentation of relevant packaging information.
  • Webpack-merge: Extracts common configuration to reduce duplicate configuration code