Webpack 4.X from beginner to proficient-third party library (vi)

Source: Internet
Author: User

Third-party libraries or frameworks are often used during development, such as familiar jquery。 They can improve development efficiency, but how to webpackUse it. This article describes two things, how to use a third-party library, and how to extract third-party libraries.

Using a third-party library 1, import directly into the portal file

Install jquery

NPM I Jquery-s

Directory structure

package.jsonThe contents are as follows:

{  "name": "webpack-demo",  "version": "1.0.0",  "description": "",  "main": "webpack.config.js",  "scripts": {    "build": "webpack --mode production",    "dev": "webpack-dev-server --mode development"  },  "keywords": [],  "author": "",  "license": "ISC",  "devDependencies": {    "css-loader": "^1.0.0",    "file-loader": "^1.1.11",    "html-webpack-plugin": "^3.2.0",    "mini-css-extract-plugin": "^0.4.1",    "url-loader": "^1.0.1",    "webpack": "^4.16.3",    "webpack-cli": "^3.1.0",    "webpack-dev-server": "^3.1.5"  },  "dependencies": {    "jquery": "^3.3.1"  }}

webpack.config.jsThe contents are as follows:

Const Path=require (' path '); const htmlwebpackplugin=require (' Html-webpack-plugin '); Const minicssextractplugin= Require (' Mini-css-extract-plugin '); module.exports={entry: './src/js/index.js ', output:{path:path.resolve (__d            Irname, ' dist '), filename: ' Js/index.js '}, plugins:[new Htmlwebpackplugin ({title: ' Chen Xuihui ',            Template: './src/template.html ', filename: ' index.html '}, new Minicssextractplugin ({ FileName: ' Css/index.css '}),], devserver:{host: ' localhost ', port:1573, open:tr                        UE}, module:{rules:[{test:/\.css$/, use:[{ Loader:MiniCssExtractPlugin.loader, options:{Publ Icpath: '.            /'}, ' Css-loader ',]}, {test:/\.                        (jpg|png|gif) $/, use:[{loader: ' Url-loader ',                        options:{Limit:5 * 1024x768, OutputPath: ' Images ' }                    }                ]            }        ]    }}

templage.htmlThe contents are as follows:

<!DOCTYPE html>

index.cssThe contents are as follows:

#box{ width: 800px; height: 500px; border: 5px solid #999; color: #00f; background: url(../images/img_01.jpg);}

index.jsThe contents are as follows:

import ‘../css/index.css‘;import $ from ‘jquery‘; //引入jquery$(‘ul li:last-child‘).css(‘background‘,‘green‘);

npm run buildAfter opening the page you will see li that the last label has a green background. If you open index.js the file you will find jquery the code is also compressed in.

This is a way to introduce a third-party library, but there is a problem with this approach, and if I just introduced it and didn't use it, I would still pack the third-party library in the packaging. If your code is taken over by the second classmate, he will not directly delete the error in order to avoid mistakes, import but will use this library code to delete, if the library's code is only left import , the packaging of the file size is still very large, is a waste

Modify the index.js following:

import ‘../css/index.css‘;import $ from ‘jquery‘; //引入jquery//$(‘ul li:last-child‘).css(‘background‘,‘green‘);

npm run buildAfter opening index.js , you will find jquery that the code is still packaged

2, Webpack. Provideplugin
  1. Automatic loading of modules without the need for import or require
  2. If the loaded module is not used, it will not be packaged
  3. The module that is loaded is a global module and can be used globally

Modify the webpack.config.js following:

const path=require(‘path‘);const HtmlWebpackPlugin=require(‘html-webpack-plugin‘);const MiniCssExtractPlugin=require(‘mini-css-extract-plugin‘);const webpack=require(‘webpack‘);   //引入webpack模块,ProvidePlugin是webpack身上的一个插件module.exports={    entry:‘./src/js/index.js‘,    output:{        path:path.resolve(__dirname,‘dist‘),        filename:‘js/index.js‘    },    plugins:[        new HtmlWebpackPlugin({            title:‘陈学辉‘,            template:‘./src/template.html‘,            filename:‘index.html‘        }),        new MiniCssExtractPlugin({            filename:‘css/index.css‘        }),        new webpack.ProvidePlugin({ //它是一个插件,所以需要按插件的用法new一个            $:‘jquery‘, //接收名字:模块名        }),    ],    devServer:{        host:‘localhost‘,        port:1573,        open:true    }    ...

The contents of the amendment index.js are as follows:

import ‘../css/index.css‘;$(‘ul li:last-child‘).css(‘background‘,‘green‘);

npm run buildAfter opening index.html you can see the same effect
Re-modify the index.js contents as follows:

import ‘../css/index.css‘;//$(‘ul li:last-child‘).css(‘background‘,‘green‘);

npm run buildAfter opening index.js can see jquery the content is not packaged in. This approach is smarter than the previous one, depending on whether you use the library and decide whether to package it or not.

Extracting third-party libraries

There are two forms of extracting a third-party library, the first is to introduce multiple libraries in a single page, and eventually all the code will be packaged into a file, and if the library is very large, the file will be very big and not conducive to loading. The second is the introduction of the same library on multiple pages, which will pack the library multiple times, resulting in wasted resources. Therefore, we need to extract the third-party library separately and optimize the resources.

1. One page introduces multiple libraries

Then the above code, and then add a library, the name of the library, underscore which encapsulates a lot of information about arrays and objects, I took one of the methods to demonstrate

NPM I Underscore-s

Modify webpack.config.js the plugin in:

new webpack.ProvidePlugin({ //它是一个插件,所以需要按插件的用法new一个    $:‘jquery‘, //接收名字:模块名    _:‘underscore‘  //引入underscore库}),

Modify the index.js following

import ‘../css/index.css‘;$(‘ul li:last-child‘).css(‘background‘,‘green‘);console.log(_([1,2,3]).map(v=>v*3));    //使用underscore库里的map方法,此方法为循环数组里每一位数据,并把每位数据都乘以3,返回新数组

npm run buildAfter opening index.html can see the console has output [3, 6, 9] , indicating that the underscore library has been packaged index.js in. You can annotate jquery and underscore use the code separately, and then npm run build compare index.js the size to see the difference

Extracting third-party libraries

Optimization optimization

  • Splitchunks Cache Group
  • Conditions that can be extracted
    1, the module is repeated reference or from the Node_modules module
    2, at least 30kb before the module compression
    3, on-demand (asynchronous) requests are less than 5
    4. When initializing the load, the number of concurrent requests is less than or equal to 3

webpack.config.jsin the change.moudle.exports

module.exports={    entry:{        index:‘./src/js/index.js‘,  //要把入口文件与第三方库分开,所以要单独的给名字    },    output:{        path:path.resolve(__dirname,‘dist‘),        filename:‘js/[name].js‘ //以key做为输出的名字    },    plugins:[        //...        new webpack.ProvidePlugin({            $:‘jquery‘,            _:‘underscore‘        }),    ],    devServer:{        //...    },    module:{        //...    },    optimization:{  //优化        splitChunks:{            cacheGroups:{//缓存组,一个对象。它的作用在于,可以对不同的文件做不同的处理                commonjs:{                    name:‘vender‘,      //输出的名字(提出来的第三方库)                    test: /\.js/,       //通过条件找到要提取的文件                    chunks:‘initial‘    //只对入口文件进行处理                }            }        }    }}

npm run buildAfter that there are two files, with which the index.js vender.js vender.js code is put jquery underscore .

Description
optimizationIs webpack another configuration parameter, and its meaning lies in optimization. The parameter values inside are used to extract some of the settings of the splitChunks third-party library, such as: to extract synchronous or asynchronous modules, the number of references to this module can be extracted and so on. However, the parameters placed here will take effect for all modules to be extracted. If different public modules are treated differently, they need to be defined in the splitChunks.cacheGroups
cacheGroupsTranslation is the cache group, can be understood as a different to extract the public part of the separate settings, such as the above example to the JS for the extraction, so the name commonjs is called, it is an object, which is placed in a separate configuration parameters

For more information, please refer to: https://webpack.js.org/plugins/split-chunks-plugin/

2, multiple pages simultaneously introduce a library

There is another form, like jquery , which is introduced in multiple pages, because packaging can only be packaged for single pages, which is packaged once per page jquery , resulting in wasted resources

New a.js with b.js , content as follows:
a.js

import $ from ‘jquery‘;console.log(‘这是a.js‘);console.log($(‘ul‘));

b.js

import $ from ‘jquery‘;console.log(‘这是b.js‘);console.log($(‘ul li‘));

You can see that two js files have been introduced into the jquery file

Modify webpack.config.js the file'smodule.exports

module.exports={entry:{A: './src/js/a.js ', B: './src/js/b.js '}, output:{Path:path.resolve ( __dirname, ' dist '), filename: ' Js/[name].js '}, plugins:[//requires two pages, so write two new htmlwebpackplugin/*n         EW Htmlwebpackplugin ({title: ' Chen Xuihui ', Template: './src/template.html ', filename: ' index.html '            }), */New Htmlwebpackplugin ({title: ' a page ', Template: './src/template.html '), FileName: ' a.html ', chunks:[' a '],//introduction of the corresponding JS, need to use chunks}), new Htmlwebpackplugin ({t        Itle: ' b page ', Template: './src/template.html ', filename: ' b.html ', chunks:[' B '],}),        New Minicssextractplugin ({filename: ' css/index.css '}),//jquery has been introduced separately in A and B files, which is not required here. /*new Webpack. Provideplugin ({$: ' jquery ',//Receive Name: module name _: ' Underscore '}), */], devserver:{//.    . },   module:{//...},} 

npm run buildAfter the structure, such as, in the dist next js directory to look at a.js the size of each b.js , these two files are included jquery . Then separate open a.html with the b.html page to run normally, the console print out the desired content.

This is a waste, we can completely separate jquery, in two pages respectively introduced. If multiple pages are introduced to the same library, then extracting the public library is just a requirement.

Modified webpack.config.js bymodule.exports

module.exports={entry:{A: './src/js/a.js ', B: './src/js/b.js '}, output:{Path:path.resolve (            __dirname, ' dist '), filename: ' js/[name].js '//with key as the output name}, plugins:[new Htmlwebpackplugin ({   Title: ' A page ', Template: './src/template.html ', filename: ' a.html ', chunks:[' a ', ' vender ', Vender for the extracted public part, need to be introduced in the page}), new Htmlwebpackplugin ({title: ' B Page ', Template: './src/ Template.html ', filename: ' b.html ', chunks:[' B ', ' Vender '],}), New Minicssextractplugin    ({filename: ' css/index.css '}),], devserver:{//...}, module:{//...},                    optimization:{splitchunks:{cachegroups:{common:{name: ' Vender ', Test:/\.js/, chunks: ' Initial '}}}}

npm run buildAfter the structure of the directory such as, look at a.js b.js the size again, compared to the front is a lot smaller? The public jquery has been extracted and put vender.js in. View a.html and b.html page source code Discovery vender.js has been introduced.

Webpack 4.Xall the content has been finished.

SOURCE Download: Https://pan.baidu.com/s/1h9PSkbkrhQ1IX7rzOQqk9Q

Webpack 4.X from beginner to proficient-third party library (vi)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.