Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze Webpack code separation

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)05/31 Report--

This article is to share with you about how to analyze Webpack code separation, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Webpack code separation

Tip:

Version problem

The following is based on version 2.x of webpack. Webpack 2.x has a significant change compared with webpack 1.x. So, if you have used webpack 1.x in your project, the examples in this tutorial will not apply, please be careful.

If you are determined to upgrade webpack, please refer to the webpack official documentation-migrating from v1 to v2

Read advice

It is recommended to read the concept of Webpack before reading.

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

You can separate your code into different bundle, and then you can load these 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 with caching and parallel loading.

Separate CSS (CSS Splitting)

You may also want to separate your style code into a separate bundle to make it independent of the application logic. This enhances the cacheability of styles and enables browsers to load style files in application code in parallel, avoiding FOUC problems (flickering caused by unstyled content).

Install ExtractTextWebpackPlugin as follows

$npm install-save-dev extract-text-webpack-plugin

Webpack.config.js needs to be configured as follows:

Const ExtractTextPlugin = require ('extract-text-webpack-plugin') Module.exports = {/ / about module configuration module: {/ / module rules (configure loader, parser, etc.) rules: [{/ / css load test: /\ .css $/, use: ExtractTextPlugin.extract ({use: "css-loader"})}]} / / add plug-in list plugins: [/ / package the style file separately new ExtractTextPlugin ("styles.css")]}

Example DEMO09: (DEMO / SOURCE)

Detach third-party libraries (Vendor Code Splitting)

A typical application, due to framework / functional requirements, relies on the code of many third-party libraries. Unlike application code, these third-party library code is not frequently modified.

If we keep the code in these libraries (library) in a bundle separate from the application code, we can use the browser cache mechanism to cache these files on the user's machine for a long time.

To accomplish this goal, the hash part of the vendor file name must remain the same no matter 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 execution / / webpack starts packaging / / in this case entry is multi-entry entry: {main: ". / app/index", vendor: "react"} / / options related to how webpack outputs the results output: {/ / the target path of all output files / / must be absolute (using Node.js 's path module) path: path.resolve (_ _ dirname, "dist"), / / the file name template of "entry chunk (entry chunk)" (exit chunk)? ) / / 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", / / for long-term cache}, / / add plug-in list plugins: [new webpack.optimize.CommonsChunkPlugin ({name: "vendor" / / specify the name of the public bundle. })]}

In the above configuration

In the entry property, specify react as a separate entry vendor

Then, in the output attribute, specify filename as [name]. [chunkhash:8] .js, which represents the file name style of the output file.

Finally, the CommonsChunkPlugin plug-in is introduced into 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 types of resource separation require the user to specify the separation module in advance in the configuration, you can also create a dynamic separation module in the application code.

This can be used for finer-grained blocks of code, such as routing based on our application, or prediction based on user behavior. This allows users to load non-essential resources according to their actual needs.

In the previous section, we learned that webpack can split resources into bundle. Next, we will learn how to load asynchronously. For example, this allows you to provide a minimum boot bundle first, and then load other functions asynchronously later.

Webpack supports two similar technologies for this: using import () (recommended, ECMAScript proposal) and require.ensure () (legacy, webpack specific). This article only introduces the officially recommended import () method.

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

Webpack treats import () as a split-point and the introduced module as a separate chunk. Import () takes the module name as a parameter and returns a Promoise object, namely import (name)-> Promise

Use with Babel

If you want to use import in Babel, but because import () is still a feature of Stage 3, you need to install / add the syntax-dynamic-import plug-in to avoid parser errors. After the draft has officially become the specification, this plug-in is no longer needed.

Example:

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 () {/ / dynamically introduces 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 (It is {this.state.date}). Click here to changing the time.

);}}

Webpack.config.js

/ / about module configuration module: {/ / Module rules (configure loader, parser, etc.) rules: [{/ / semantic interpreter to automatically convert the es2015/react syntax in the js/jsx file into the Javascript syntax recognized by the browser test: /\ .jsx? $/, include: path.resolve (_ _ dirname, "app"), / / the loader that should be applied It is relative to context resolution / / for clarity, the `- loader` suffix is no longer optional in webpack 2 / / check the webpack 1 upgrade guide. Loader: "babel-loader", / / loader optional options: {presets: ["es2015", "react"], plugins: ['syntax-dynamic-import']},},]}, which is how to analyze Webpack code separation. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report