Webpack Code Separation

Source: Internet
Author: User

Webpack Code Separation

Tips:

  1. Version issue

This article is based on the Webpack 2.x version. Webpack 2.x has significant changes compared to Webpack 1.x. So, if you've already used Webpack 1.x in your project, the examples in this tutorial will not apply, please be careful.

If the heart wants to upgrade webpack, please refer to Webpack official documentation-Migrating from V1 to v2

  1. Read suggestions

Before reading this article, it is recommended to read the Webpack concept first.

Code separation is one of the most compelling features in Webpack.

You can separate your code into different bundles, and then you can load the files on demand.

In general, webpack separation can be divided into two categories:

    • Resource separation

    • Code separation

Resource separation (Resource splitting)

Code separation of third-party libraries (vendor) and CSS helps in caching and parallel loading.

Detach css (CSS splitting)

You might also want to separate your style code into a separate bundle so that it is independent of the application logic. This enhances the caching of the styles and allows the browser to load style files in the application code in parallel, avoiding fouc problems (flicker caused by no style content).

Install Extracttextwebpackplugin as follows

$ NPM Install--save-dev Extract-text-webpack-plugin

The webpack.config.js needs to be configured as follows:

Const Extracttextplugin = require (' Extract-text-webpack-plugin '); module.exports = {//About modules Configuration module: {//Module rules (Configuration lo Ader, parser, and other options) rules: [{//CSS Load test:/\.css$/, Use:ExtractTextPlugin.extract ({u  SE: "Css-loader"})}]},//Add-on List plugins: [//package style file separately new Extracttextplugin ("Styles.css") ]};

Example DEMO09: (Demo/source)

Separate third-party libraries (Vendor Code splitting)

A typical application, due to the framework/functional requirements, will depend on the code of many third-party libraries. Unlike application code, these third-party library code does not change frequently.

If we keep the code in these libraries (library) in bundles that are separate from the application code, we can use the browser caching mechanism to cache these files for long periods on the user's machine.

To accomplish this goal, the hash portion of the vendor file name must remain intact, regardless of how the application code changes. Learn how to use Commonschunkplugin to separate vendor/library code.

Webpack.config.js

Const webpack = require (' Webpack ');module.exports = {  //  here the application starts to execute   // webpack  start packing   //  in this case  entry  for multi-entry   entry: {     main:  "./app/index",    vendor:  "React"   },     // webpack  How to output the results related options   output: {    //   Destination path for all output files     //  must be an absolute path (using  Node.js   path  module)      path: path.resolve (__dirname,  "dist"),     // "inlet tile (entry  Chunk) "FileName template (export chunking?) )     // filename:  "Bundle.min.js",     // filename:   "[name].js", //  for multiple entry points (Entry point) (Exit point?) )     // filename:  "[Chunkhash].js", //  for long-term cache      filename:  "[name]. [Chunkhash:8].js], //  forLong-Acting cache   },  //  Add-ons list   plugins: [    new  Webpack.optimize.CommonsChunkPlugin ({      name:  "Vendor"  //  designated public  bundle  's name.     })   ]};

In the above configuration,

    1. In the entry attribute, specify react as an independent entry vendor;

    2. Then, in the Output property, specify filename as [name]. [Chunkhash:8].js, which represents the filename style of the output file.

    3. Finally, the Commonschunkplugin plugin is introduced in the plugins list to specify the bundle.

After executing the webpack command, Webpack generates 2 bundle files in the form of:

Main.bef8f974.jsvendor.2f1bd4c8.js

Example DEMO10: (Demo/source)

Code Separation on Demand (on Demand code splitting)

Although the previous categories of resource separation require the user to specify the detach module in the configuration beforehand, it is also possible to create a dynamic detach module in the application code.

This can be used for finer-grained blocks of code, for example, based on our application routing, or based on user behavior predictions. This allows the user to load non-essential resources as needed.

In the previous section, we learned that Webpack can split resources into bundles. Next, we'll learn how to load asynchronously. This allows, for example, a minimum of boot bundles to be provided first, and other features to be loaded asynchronously at a later time.

Webpack supports two similar techniques for this purpose: using Import () (recommended, ECMAScript proposal) and Require.ensure () (Legacy, Webpack-specific). This article only describes the officially recommended import () method.

The ES2015 loader specification defines the import () as a way to dynamically load the ES2015 module at runtime (runtime).

Webpack takes import () as a separation point (split-point) and takes the introduced module as a separate chunk. Import () takes the module name as an argument and returns a Promoise object, which is import (name), Promise

Use with Babel

If you want to use import in Babel, but because import () is still part of Stage 3, you need to install/Add Syntax-dynamic-import plugin to avoid parser error. This plugin is no longer needed after the draft has formally become a specification.

Cases:

Let's define a Clock component and dynamically introduce the moment library.

First, install the moment library.

$ NPM Install--save-dev moment

JavaScript Code:

Class clock extends react.component {  constructor (props)  {     super (props);     this.state = { date: new date (). toLocaleDateString ()  };    this.click = this.click.bind (this);   }   click ()  {    //  Dynamic introduction of import ()     import (' moment ')       .then (Moment => moment (). Format ("Mmmm do yyyy,  h:mm:ss a "))       .then (Str => this.setstate ({date:str}) )       .catch (Err => console.log ("failed to load  Moment ",  err));   }  render ()  {    return  (       <div>        

Webpack.config.js

  About module Configuration module: {  //  module rules (configuration  loader, parser, etc.)   rules: [     {      //  semantic interpreter, the  es2015/react in the  js/jsx  file   Grammar automatically transitions to browser-aware  Javascript  syntax       test: /\.jsx?$/,       include: path.resolve (__dirname,  "app"),       //  should apply  loader, which is relative to context resolution       //  in order to be clearer, '-loader '   suffix in  webpack 2  is no longer an optional       //  view  webpack 1  upgrade Guide.       loader:  "Babel-loader",      //  Options for loader        options: {         presets: ["es2015",  "React"],        plugins: [' Syntax-dynamic-import ']      },    },  ]}, 


Webpack Code Separation

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.