Code optimization for the Webpack configuration

Source: Internet
Author: User
Tags glob

Previous words

The basic configuration of Webpack is described earlier in this article to detail the configuration of code optimization in Webpack

Packaging Common Code

The Commonschunkplugin plugin is an optional feature for creating a standalone file (also known as Chunk), which includes common modules for multiple ingress chunk. By splitting the public module, the resultant file can be loaded at the very beginning and stored in the cache for later use. This leads to a speed boost because the browser quickly pulls the public code out of the cache instead of loading a larger file every time a new page is accessed

new webpack.optimize.CommonsChunkPlugin (options)

"Configuration Items"

{name:string,//orNamesstring[],  // name of the common chunk
FileName:string, //common the file name template for chunk. Can contain the same placeholder as ' output.filename 'Minchunks:number| Infinity|function (module, Count)Boolean,//The minimum number of chunks required to be included before the public Chunk (Commons chunk) is passed in. //quantity must be greater than or equal to 2, or less than or equal to chunkschunks:string[], //Select the source of chunks by chunk name. Chunk must be a sub-module of the public chunk.
Children:boolean,//if set to ' true ', all public chunk submodules will be selectedDeepchildren:boolean,//If ' true ' all descendants of the Commons chunk is selected Async: boolean|string, //if set to ' true ', an asynchronous public chunk will be created as a submodule of ' options.name ', and the ' options.chunks ' sibling module. Minsize:number,//The minimum size of all public modules (common module) before public chunk are created. }

"Extract Public Code"

New Webpack.optimize.CommonsChunkPlugin ({  "Commons",  //    (the name of the public chunk (commnons chunk)"commons.js",   // (public chunk file name)})

"Clear third-party library chunk"

entry: {  vendor: ["jquery""other-lib"],   " ./entry " },plugins: [  new  webpack.optimize.CommonsChunkPlugin ({    " Vendor " ,    minchunks:infinity,  })]

"Package public modules into parent chunk"

New Webpack.optimize.CommonsChunkPlugin ({  true,})

"Extra Async public Chunk"

New Webpack.optimize.CommonsChunkPlugin ({  "app",  // or  Names: ["app""subpagea"]   true ,   Async true ,   3 ,})

"Wepack4"

Webpack 4 will remove the commonschunkplugin and replace it with two new configuration items optimization.splitchunks and Optimization.runtimechunk

To start the default code splitting configuration item by setting Optimization.splitChunks.chunks: "All"

Webpack will automatically pack chunks when the following conditions are met:

53

By setting Optimization.runtimeChunk:true to add a runtime-only chunk for each portal

Dynamic Import

The commonschunkplugin described above can be de-weighed and separated chunk. The dynamic import described in this section is used to isolate the code through the inline function of the module

Webpack provides two similar technologies. For dynamic import, the first and preferred option is to use the import () syntax that conforms to the ECMASCRIPT proposal. The second is to use Webpack-specific require.ensure

The following is a dynamic import using the import () syntax.

  ConstPath = require ('Path'); ConstHtmlwebpackplugin = require ('Html-webpack-plugin'); Module.exports={entry: {index:'./src/index.js'}, plugins: [NewHtmlwebpackplugin ({title:'Code Splitting'})], output: {filename:'[Name].bundle.js', Chunkfilename:'[Name].bundle.js', Path:path.resolve (__dirname,'Dist')    }  };

below to dynamically import loadsh

function Getcomponent () { 
returnImport/*webpackchunkname: "Lodash"*/ 'Lodash'). Then (_ = { varelement = Document.createelement ('Div');element.innerhtml = _.join (['Hello','Webpack'],' '); returnelement;}).Catch(Error ='An error occurred while loading the component'); }Getcomponent (). Then (component = {Document.body.appendChild (component);})

Used in comments webpackChunkName . Doing so will cause the bundle to be named lodash.bundle.js , not[id].bundle.js

Lazy Loading

Lazy loading or loading on demand is a great way to optimize your Web page or application. This approach is actually to take your code out of some logical breakpoints first, and then in some blocks of code to complete some operations, immediately refer to or will refer to another new block of code. This speeds up the initial load of the application, easing its overall volume, because some code blocks may never be loaded

The LOADSH, which is dynamically imported above, does generate a separate block of code when the script is run lodash.bundle.js and "lazy-load" it on the technical concept. The problem is that loading this package does not require user interaction--meaning that it is requested every time the page is loaded

To add an interaction, use the console to print some text when the user taps the button. But wait until the first interaction and then load that block of code ( print.js )

// print.jsconsole.log ('theprint.js module has loaded! See the Network tab in Dev Tools ... '  Default () = {  console.log ('button clicked:here\ ' s "some text"! ) ' );}
//Index.jsImport _ from 'Lodash'; function component () {varelement = Document.createelement ('Div'); varbutton = Document.createelement ('Button'); varbr = Document.createelement ('BR'); Button.innerhtml='Click me and look at the console!'; Element.innerhtml= _.join (['Hello','Webpack'],' ');   Element.appendchild (BR);   Element.appendchild (button); Button.onclick= e = Import (/*webpackchunkname: "Print"*/ './print'). Then (module = {     varPrint = module.default;   Print ();    }); returnelement; } document.body.appendChild (Component ());

Eliminate useless Code

The tree shaking is a term that is typically used to describe unreferenced code (DEAD-CODE) in the context of a JavaScript removal. It relies on static structural features in the ES2015 module system, such as import and export. This term and concept is actually emerging from the ES2015 Module Packaging tool Rollup

"JS"

JS Tree shaking mainly through the UGLIFYJS plug-in to complete

NPM Install--save-dev Uglifyjs-webpack-plugin
ConstPath = require ('Path');ConstUglifyjsplugin = require ('Uglifyjs-webpack-plugin'); Module.exports={entry:'./src/index.js', Output: {filename:'Bundle.js', Path:path.resolve (__dirname,'Dist')}, plugins: [NewUglifyjsplugin ()]};

"CSS"

CSS tree shaking is mainly implemented by purify CSS.

NPM i-d Purifycss-webpack Purify-css
ConstPath = require ('Path');ConstGlob = require ('Glob');ConstExtracttextplugin = require ('Extract-text-webpack-plugin');ConstPurifycssplugin = require ('Purifycss-webpack'); Module.exports={entry: {...}, output: {...}, module: {rules: [{test:/\.css$/, Loader:ExtractTextPlugin.extract ({fallbackloader:'Style-loader', Loader:'Css-loader'})}]}, plugins: [NewExtracttextplugin ('[name]. [Contenthash].css'),    //Make sure this is after extracttextplugin!    NewPurifycssplugin ({//Give paths to parse for rules. These should be absolute!Paths:glob.sync (Path.join (__dirname,'app/*.html')),    })  ]};

If you want to set multipathing, you need to change glob to Glob-all

const Glob = require ('glob-all');
Paths:glob.sync ([  '. php'),  '  partials/.php')])

Code optimization for the Webpack configuration

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.