Summary of webpack related knowledge

Dj0427 2020-11-10 18:13:42
summary webpack related knowledge

Have a look recently webpack Related books , Here, I would like to share my knowledge notes summarized in this process , as follows :

    Open source js Module packaging tool , Resolve dependencies between modules , Organize the modules according to specific rules and order , Finally, it merged into js file .

js modular :
    Because at first js Positioning is a small language , All without modules . This leads to a lot of drawbacks :
        1. Manual maintenance is required js Loading order of .(js Dependencies between )
        2. every last script It means that you need to ask the server for a resource , Too many requests result in slow rendering of web pages
        3. stay script In the label , The top-level scope is the global scope , Easy to cause global pollution .

    Modular advantages :
        1. Import and export can clearly see the dependency relationship between modules
        2. Modules are packaged with tools , The page only needs to load the merged resource file , Reduce network overhead
        3. The scope between multiple modules is isolated , No naming conflicts

Module packaging tool :webpack、parcel、rollup etc.

webpack Module packaging advantages :
    1. Support multiple module standards ,AMD、CommonJS、ES6 modular
    2. There are complete code partitioning solutions , It can reduce the resource volume , Improve the rendering speed of the home page
    3. Can handle all kinds of resources , Such as js、 style 、 Templates 、 Pictures, etc
    4. There's huge community support

AMD: Asynchronous modules . The way modules are loaded is asynchronous .
    Use define Define modules , Use require Function loading module
    shortcoming : The grammar is long , Easy to cause callback hell , The display is not clear enough
    advantage : Non blocking

UMD: General module standard , Make a module run in a variety of environments , When bored commonjs、AMD, Or a non Modular Environment

npm Package manager : Find libraries developed and published by others on other platforms , And install it into the project .
    adopt import When importing a module , The actual operation process is : Each module has an entry , Load a module , In fact, it is the entry file to load the module . This entry is maintained inside the module package.json Of documents main Field .

mode: Specify packaging mode , It is divided into development、production、none, It will add a series of configurations suitable for the current mode , Reduce the workload artificially

Use npm scripts
    stay package.json Add script command to
    scripts yes npm Provides script command function
    npm scripts The underlying implementation principle is to call shell To run the script command . because webpack It's just a tool to package modular code , It doesn't provide any task management functions , and npm scripts Can simplify a series of complex processes into a simple command .

Module packaging
    CommonJS: Originally, it was designed only for the server side , I know I have browserify ——— One runs on node.js Module packaging tool in the environment , It can be commonjs The module is packaged as a single file that the browser can run , So it's popular in front-end development .

    CommonJS Each file in is a module , Declared variables and functions only belong to the scope of the module itself , Invisible to the outside world .
    export : It's the only way a module can expose itself to the outside world , adopt module.exports
    CommonJS There is one. module Object is used to store the information of the current module
    Import : adopt require Do module import .require Function receives expression , So you can dynamically specify the module loading path
    Import module is divided into 2 In this case :
        1.require This is the first time that the module is loaded , The module is executed first , And then export the content ;
        2.require Has been loaded , At this time, the code of the module will not be executed again , Instead, it directly exports the result of the last execution

    ES6 Module
        ES6 It also takes each file as a module , Each module has its own scope , Will automatically adopt strict mode
    CommonJS And ES6 Module The difference between :
        1. Dynamic and static :CommonJS Module dependencies are built in the code runtime ;ES6Module Module dependencies are established during the code compilation phase
          ES6 Module advantage :
            1. Dead code detection and elimination . Use static analysis tools to detect which modules have not been called , Remove these unused modules when packaging , Reduce packing volume
            2. Module variable type check . Helps to ensure that the values or interface types passed between modules are correct ;
            3. Compile optimization .commonjs Import the same object , and module Import variables directly , Reduce the reference level , The program is efficient
        2. Value copying and dynamic mapping : When importing a module , about commonjs Is an export worth copying , and es6 Of module It is worth mapping dynamically , And this mapping is read-only ,es6 Of module Cannot make changes to imported variables

    AMD、CMD、CommonJs yes ES5 The modular programming solution provided in
        CommonJs Used on the server side ,AMD and CMD In the browser environment
        AMD- Asynchronous module definition
        CMD--- Is a synchronization module definition
        CommonJS standard --- It's through module.exports Defined , It doesn't support module.exports, adopt node.js The back end uses .Nodejs The end is to use CommonJS canonical , Front end browsers generally use AMD、CMD、ES6 To define modular development

Browser load bundle The process :
    1. In the outermost anonymous function, the browser execution environment is initialized , Do some preparation for the module loading and execution ;
    2. Load the entry module , Every bundle Each has an entry module , It will be executed from it in the browser ;
    3. Execute module code . If it's done module.exports Then record the export value of the module ; If you meet require function , Then temporarily hand over the power of execution , Get into _webpack_require_ Function body to load the logic of other modules ;
    4. stay _webpack_require_ Function will determine whether the module to be loaded exists or not installedModules in , If it exists, the value is taken directly , Or go back to the 3 Step , Execute the module code to get the exported value ;
    5. All dependent modules have been executed , Finally, the execution right goes back to the entry module . When the entry code is executed to the end , identification bundle end of execution .

    Code fragmentation : Effectively reduce the resource volume , Better use of cache , Give users a more user-friendly experience .
    1、 extract vendor.(webpack Use vendor To name the third-party libraries used in the project )
        reason : When engineering produces a js The file and the volume is big , When the code is updated , Users have to download the entire resource file again , Not friendly to page performance .
        operation :1)CommonsChunkPlugin
              1. Use CommonsChunkPlugin Extracting common modules between multiple entries
              2. In single portal applications , Extract the third-party class library and modules that are not often updated in the business
                entry: {
                    app: ['babel-polyfill','./src/main.js'],
                output: {
                    filename: '[name].js',
                    publicPath: process.env.NODE_ENV === 'production'
                    new webpack.optimize.CommonsChunkPlugin({ // Extract the third-party class library and modules that are not often updated in the business
                    name: 'vendor',
                    filename: 'vendor.js',
                    minChunks: 3 // Set extraction rules
                    new webpack.optimize.CommonsChunkPlugin({
                    name: 'commons',
                    filename: 'commons.js',
                    chunks: ['vueRouter','commonJs','busJs'] // Set the extraction range
                CommonsChunkPlugin shortcoming :
                    1. One CommonsChunkPlugin Only one can be extracted vendor, Want to extract more than one vendor You need to configure multiple plug-ins , Duplicate code
                    2. Added manifest, extract webpack Runtime , Make the browser load one more resource , Page rendering is not friendly
                    Only modify the business code , When the library code is not changed , Package out of the library code chunkhash It's also changing , Causes the long-term cache mechanism to fail
                    solve : take webpack Of runtime Extract it alone .
                    entry: {
                        app: "./app.js",
                        vendor: ["lodash","jquery"],
                    output: {
                        path: 'release',
                        filename: "[name].[chunkhash].js"
                    plugins: [
                        new webpack.optimize.CommonsChunkPlugin({names: ['vendor','runtime']}),

                    3. Will destroy chunk The dependencies of modules in , Such as under asynchronous module
                runtime: When the browser is running ,webpack All the code used to connect modular applications .runtime contain , When the modules interact , The loading and parsing logic required to connect the modules . Includes the connection of loaded modules in the browser , And the execution logic of lazy loading module .
             2) optimization.SplitChunks
                webpack4 Code slicing plug-ins provided . Powerful and easy to use .
                mode: 'development',  // For the current development environment or build environment automatically add some corresponding webpack To configure
                optimization: {
                        chunks: 'all' // SplitChunks Will be for all chunks take effect ( By default , Only for asynchronous chunks take effect , And there is no need to configure )
    2、 narrow babel-loader The scope of the : By setting exclude exclude node_module, Speed up packing
        add to babel-loader Of cacheDirectory Configuration item , Start the caching mechanism , Prevent secondary compilation of unchanged modules
       @babel/preset-env Will es6 module Turn it into commonjs, Lead to webpack Of tree-shaking Feature failure . Can be @babel-preset-env Of module Configuration item set to false Disable module language conversion .

The preprocessor loader: It can make webpack Ability to handle different resource types , More intuitive maintenance of the relationship between modules .
    Support chain operation : The chain loader stay webpack When packaging, hand over resources from back to front loader Handle , Finally came into effect loader Put it first

    because webpack Know only js, All through one or more loader Translate it .
    output = loader(input)

loader species :
    css-loader: Handle css Various loading syntax for (@import and url() Functions, etc )
    style-loader: Insert the style into the page , send css Style works . Wrap the style string as style Label insert page .
    sass-loader: take scss The grammar is compiled into css
    less-loader: take less The grammar is compiled into css
    html-loader: take html The file is converted to a string and formatted , adopt document.write Insert into page . To pass js load html fragment .
    handlebars-loader: Handle handlerbars Templates
    babel-loader: Handle es6+ The language is es5, To be compatible with different platforms
    ts-loader: Handle typescript
    file-loader: Package file type resources , And back to publicPath, Such as the use of image resources file-loader You can go to js Loading pictures in
    url-loader: And file-loader Type of action , The difference is that you can set a threshold for file size , Less than threshold return file base64 Formal coding is injected into js or css in , Reduce the number of resource loads .
    vue-loader: Handle vue Components , Set the component template 、js And style split , adopt vue-template-compiler Compiling templates

    postcss: use js Tools and plug-ins conversion css Code tools

loader To configure :
    exclude: Modules that are regularly matched are excluded
    include: Only works on regular matching modules
    resource: The module being loaded  // Accurately determine the scope of the module rules
    issuer: Loaders         // Accurately determine the scope of the module rules
    enforce: Force the designation of loader The order of action , Its value is pre、inline( The official does not recommend the use of )、nomal、post
        pre: Will be in all normal loader Before execution , Make sure that the detection code is not otherwise loader Changed
        post: In all loader After performing

source-map: Easy to view the source code in the browser console , The resulting .map file . Will compile 、 pack 、 The process of the compressed code mapping back to the source code , It is easy to trace online generation environment problems . stay devtool To configure source-map Outside , You can also choose according to your needs cheap-source-map、eval-source-map etc.

Style handling :
    reason : Hope patterns exist in css Files, not style label , Because it's good for client caching
    solve : adopt extract-text-webpack-plugin(webpack4 The previous version ) or mini-css-extract-plugin(webpack4+) plug-in unit , Extract the style to css file
    mini-css-extract-plugin advantage : Support on-demand loading css

bundle Volume monitoring :
    vs code plug-in unit import cost The size of the introduced modules can be monitored
    webpack-bundle-analyzer Tools , Help analyze bundle The composition of the

webpack Package optimization :
    1.HappyPack Multithreading packaging
        It is suitable for the project with heavy translation task , Such as ts-loader、babel-loader, Yes sass-loader and less-loader The effect is not obvious
        Optimize multiple loader Configure a id
        Packing principle : Decompose the task to multiple subprocesses for concurrent execution , After the sub process has finished processing, it will send the result to the main process .
    2. Narrow the packaging scope
        1、 By configuring include、exclude( Priority over include)
        2、 To configure noParse Filtering files that don't need parsing , Improve packaging efficiency , Such as jquery, But it's still packaged to bundle in
        3.IgnorePlugin Completely exclude some modules , Even references are not packaged into resource files , It is used to process resources that are not referenced by class libraries
        4. There are some loader You can configure the cache Set the cache , But the expiration date can't be detected

        Similar to code fragmentation , It's all about extracting common modules .
        Code fragmentation : Set rules and extract modules according to the rules in the packaging process
        DllPlugin: take vendor Take it out completely , adopt webpack Configure independent packaging , The actual project is no longer handled when it is built , Take it directly
        First use DllPlugin Package static resources , Reuse DllReferencePlugin Let the source file reference the resource file

        step : Reference link
        1) stay build Create under folder webpack.dll.conf.js file
        const path = require('path');
        const webpack = require('webpack');
        module.exports = {
            entry: {
            }, // Third party Library
            output: {
                path: path.join(__dirname,'../static/js'),
                filename: '[name].dll.js',
                library: '[name]_library'
                new webpack.DllPlugin({
                name: '[name]_library',
                path: path.join(__dirname,'[name]-manifest.json'),
                context: __dirname
                // Compress packed files
                new webpack.optimize.UglifyJsPlugin({
                    warnings: false
        2) stay webpack.base.conf.js In file
            new webpack.DllReferencePlugin({
            manifest: require('./vendor-manifest.json'),

        3) stay package.json Add command to file
        "vuedll":"webpack --config build/webpack.dll.conf.js"
        4) Use npm run vuedll pack
        5) stay index.html Introduce in the file <script src="./static/js/vendor.dll.js"></script>
    4、tree shaking
        Modules not used in the detection process , When resources are compressed from bundle Medium removal .
        npm Package supply commonjs and es6 module Two forms of derivation , and tree shaking Only in es6 It works in form . because es6 The dependency of is built at compile time , Not the runtime .
        If used babel-loader,webpack It will translate into commonjs Modules of form , Cannot be tree-shaking, You can configure to disable
        stay presets:[
        This allows you to use tree shaking Tag code , Then through the compression tool to remove dead code terser-webpack-plugin, stay webpack4 Lieutenant general mode Set to production It can also achieve the effect
    5、webpack When auto refresh is started ( When the source file changes , Automatically rebuild new output files ), adopt watchOptions Configure to narrow down the range of files you need to listen to
          watchOptions: {
            // Don't listen to files or folders , Support regular matching
            // The default is empty.
            ignored: /node_modules/,
            // Listen for changes and wait 300ms And then do the action , Prevent too frequent recompilation due to too fast file updates
            // The default is 300ms
            aggregateTimeout: 300,
            // To determine whether a file has changed is realized by constantly asking the system whether a specified file has changed
            // Default every 1000 Ask once in a millisecond
            poll: 1000
    6、 Open module hot swap
        devserver Support module hot replacement technology , Preview in real time without refreshing the entire page . principle : When a source code changes , Recompile only changed modules , Then replace the old module in the browser with the output module
    7、 Use cdn Speed up
        adopt publicpath The parameter is used to set the storage of static resources cdn Catalog url.
        because cdn Services generally allow resources to be cached for a long time , Lead to index.html Even if the file is rewritten , But still running the previous version . terms of settlement : take index.html Deploy on your own server , take static Files in are deployed in cdn On , And the file name uses hash value . After the content changes like this , The file name will also change .

Code checking :
    1. Check code segmentation : Indent code , code annotation
    2. Potential problems : Analysis of the code in the process of running the potential bug
1、 Check js
    Check tools :eslint
2、 Check ts
    Check tools TSLint
3、 Check css
    Check tools stylelint

Loading pictures :
    webpack When loading image resources , There are two ways :

    1) file-loader Will be able to js and css Replace the statement of importing picture with the correct address , And output the file to the corresponding location at the same time
        Such as :css File source code :
        #app {
            background-image: url(./imgs/a.png);
        By file-loader Convert the output of css
        #app {
            background-image: url(5556e1251a78c5afda9ee7dd06ad109b.png);
        At the same time dist in ./imgs/a.png There is more in the document 5556e1251a78c5afda9ee7dd06ad109b.png
    2) url-loader Pass the contents of the document through base64 Code and inject into js or css in
        Such as :#app {
                background-image: url(./imgs/a.png);
            after url-loader after
            #app {
                background-image: url(data:image/png;base64,iVBORw01afer...); /* The rest is omitted at the end base64 Encoded data */
    url-loader Inject small image resources into the code , Reduce the number of loads . Because every time you load a resource, you have to create it http Connect .
    Can pass imagemin-webpack-plugin Compress images to optimize loading of images

webpack File monitoring principle (devserver)
    Get the last editing time of this file regularly , Save the latest last edit time every time , If it is found that the last editing time between the current acquisition and the last save is inconsistent , I think this document has changed . When the file is found to have changed , It's not going to tell the listener right away , Instead, cache it first , After collecting changes over time , Tell the listener once again ,watchOptions.aggregateTimeout This is how to configure the waiting time .
    webpack Will be configured from entry Document departure , Recursively parse out entry Dependent files , Add all of these dependencies to the listening list

webpack Process Overview
    1、 Initialize parameters
        From configuration files and shell Read and merge parameters in statement , Get the final parameters ;

    2、 Start compilation
        Initialize with the parameters obtained in the previous step compiler object , Load all configuration plug-ins , Of the execution object run Method to start compilation ;

    3、 Fixed entrance
        According to the configuration entry Find out all the entry files ;

    4、 Compiler module
        Starting from the entry file , Call all configured loader Translate the module , Then find out the modules that the module depends on . Then recurs this step until all the files that the entry depends on are processed in this step ;

    5、 Complete module compilation
        After translating all the modules , Get the final content of each module after being translated and the dependency relationship between them

    6、 Output resources
        According to the dependency relationship between the entry and the module , Assemble into chunk, And then put each chunk Convert to a separate file to add to the output list

    7、 Output complete
        According to the configuration , Determine the output path and file name , Write the contents of the file to the file system .



  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple