Home Web Front-end JS Tutorial How to optimize packaging using React and Webpack?

How to optimize packaging using React and Webpack?

Jun 11, 2018 am 10:09 AM
react webpack

This article mainly introduces a brief discussion of React Webpack construction and packaging optimization. Now I share it with you and give you a reference.

This article introduces the React Webpack construction and packaging optimization and shares it with you. The details are as follows:

Use babel-react-optimize to optimize React code

Check unused libraries and remove import references

Package used libraries on demand, such as lodash and echart Wait

lodash can be optimized using babel-plugin-lodash.

It should be noted that

The babel-plugin-transform-react-remove-prop-types plugin is used in babel-react-optimize. Normally, if you don't reference the component's PropTypes in your code, it's totally fine. Using this plugin may cause problems if your component uses it.

See:

https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types#is-it-safe

Webpack build and package optimization

The problems in Webpack build and package mainly focus on the following two aspects:

  1. Webpack build speed is slow

  2. The file size after Webpack package is too large

Webpack build speed is slow

You can use Webpack.DDLPlugin, HappyPack to improve build speed. For details, please refer to Xiaoming’s documentation on DMP DDLPlugin. The original text is as follows:

Webpack.DLLPlugin

Adding a webpack.dll.config.js
mainly uses a DllPlugin plug-in to independently package some third-party resources and place them at the same time In a manifest.json configuration file,

In this way, after updating in the component, these third-party resources will not be rebuilt,

  1. At the same time, configure dll/vendors independently .js file, provided to webpack.dll.config.js

  2. Modify package.json

Add: "dll": "webpack --config webpack.dll.config.js --progress --colors ", .

After executing npm run dll, two files vendor-manifest.json and vendor.dll.js will be produced in the dll directory.

Configure the webpack.dev.config.js file and add one DllReferencePlugin plug-in, and specify the vendor-manifest.json file

new webpack.DllReferencePlugin({
 context: join(__dirname, 'src'),
 manifest: require('./dll/vendor-manifest.json')
})
Copy after login

Modify html

<% if(htmlWebpackPlugin.options.NODE_ENV ===&#39;development&#39;){ %>
 <script src="dll/vendor.dll.js"></script>
<% } %>
Copy after login

Note that you need to configure the NODE_ENV parameter in the htmlWebpackPlugin plug-in

Happypack

Improve rebuild efficiency through multi-threading, caching, etc. https://github.com/amireh/happypack

Create multiple HappyPacks for different resources in webpack.dev.config.js , For example, 1 js, 1 less, and set the id

new HappyPack({
 id: &#39;js&#39;,
 threadPool: happyThreadPool,
 cache: true,
 verbose: true,
 loaders: [&#39;babel-loader?babelrc&cacheDirectory=true&#39;],
}),
new HappyPack({
 id: &#39;less&#39;,
 threadPool: happyThreadPool,
 cache: true,
 verbose: true,
 loaders: [&#39;css-loader&#39;, &#39;less-loader&#39;],
})
Copy after login

Configure use as happypack/loader in module.rules, set the id

{
 test: /\.js$/,
 use: [
 &#39;happypack/loader?id=js&#39;
 ],
 exclude: /node_modules/
}, {
 test: /\.less$/,
 loader: extractLess.extract({
 use: [&#39;happypack/loader?id=less&#39;],
 fallback: &#39;style-loader&#39;
 })
}
Copy after login

to reduce the number of Webpack packages File size

First we need to analyze our entire bundle, what it consists of and the size of each component.

Webpack-bundle-analyzer is recommended here. After installation, just add the plug-in in webpack.dev.config.js, and the analysis results will be automatically opened on the website after each startup, as shown below

plugins.push( new BundleAnalyzerPlugin());
Copy after login

Except In addition, you can also output the packaging process into a json file

webpack --profile --json -> stats.json
Copy after login

and then go to the following two websites for analysis

  1. webpack/analyse

  2. Webpack Chart

Through the above chart analysis, we can clearly see the components and corresponding sizes of the entire bundle.js.

The solution to the excessive size of bundle.js is as follows:

  1. Enable compression and other plug-ins in the production environment and remove unnecessary plug-ins

  2. Split business code and third-party libraries and public modules

  3. webpack Turn on gzip compression

  4. Load on demand

Enable compression and other plug-ins in the production environment, and remove unnecessary plug-ins.

Make sure to start webpack.DefinePlugin and webpack.optimize.UglifyJsPlugin in the production environment.

const plugins = [
 new webpack.DefinePlugin({
  &#39;process.env.NODE_ENV&#39;: JSON.stringify(process.env.NODE_ENV || &#39;production&#39;)
 }),
  new webpack.optimize.UglifyJsPlugin({
  compress: {
   warnings: false,
   drop_console: false //eslint-disable-line
  }
  })   
]
Copy after login

Split business code and third-party libraries and public modules

Because the project's business code changes frequently, the code changes of the third-party library are relatively unchanged. So frequency. If the business code and the third library are packaged into the same chunk, at each build, even if the business code only changes one line, even if the code of the third-party library does not change, the hash of the entire chunk will be different from the last time. . This is not the result we want. What we want is that if the code of the third-party library does not change, then we must ensure that the corresponding hash does not change when building, so that we can use the browser cache to better improve page loading performance and shorten page loading time.

Therefore, the code of the third library can be split into vendor chunks separately and separated from the business code. In this way, no matter how the business code changes, as long as the third-party library code does not change, the corresponding hash will remain unchanged.

First, the entry configures two apps and two vendor chunks

entry: {
 vendor: [path.join(__dirname, &#39;dll&#39;, &#39;vendors.js&#39;)],
 app: [path.join(__dirname, &#39;src/index&#39;)]
},
output: {
 path: path.resolve(__dirname, &#39;build&#39;),
 filename: &#39;[name].[chunkhash:8].js&#39;
},
Copy after login

vendros.js is your own definition of which third-party libraries need to be included in the vendor, as follows:

require(&#39;babel-polyfill&#39;);
require(&#39;classnames&#39;);
require(&#39;intl&#39;);
require(&#39;isomorphic-fetch&#39;);
require(&#39;react&#39;);
require(&#39;react-dom&#39;);
require(&#39;immutable&#39;);
require(&#39;redux&#39;);
Copy after login

Then split the third library through CommonsChunkPlugin

plugins.push(
 // 拆分第三方库
 new webpack.optimize.CommonsChunkPlugin({ name: &#39;vendor&#39; }),
 // 拆分 webpack 自身代码
 new webpack.optimize.CommonsChunkPlugin({
  name: &#39;runtime&#39;,
  minChunks: Infinity
 })
);
Copy after login

上面的配置有两个细节需要注意

  1. 使用 chunkhash 而不用 hash

  2. 单独拆分 webpack 自身代码

使用 chunkhash 而不用 hash

先来看看这二者有何区别:

  1. hash 是 build-specific ,任何一个文件的改动都会导致编译的结果不同,适用于开发阶段

  2. chunkhash 是 chunk-specific ,是根据每个 chunk 的内容计算出的 hash,适用于生产

因此为了保证第三方库不变的情况下,对应的 vendor.js 的 hash 也要保持不变,我们再 output.filename 中采用了 chunkhash

单独拆分 webpack 自身代码

Webpack 有个已知问题:

webpack 自身的 boilerplate 和 manifest 代码可能在每次编译时都会变化。

这导致我们只是在 入口文件 改了一行代码,但编译出的 vendor 和 entry chunk 都变了,因为它们自身都包含这部分代码。

这是不合理的,因为实际上我们的第三方库的代码没变,vendor 不应该在我们业务代码变化时发生变化。

因此我们需要将 webpack 这部分代码分离抽离

new webpack.optimize.CommonsChunkPlugin({
   name: "runtime",
   minChunks: Infinity
}),
Copy after login

其中的 name 只要不在 entry 即可,通常使用 "runtime" 或 "manifest" 。

另外一个参数 minChunks 表示:在传入公共chunk(commons chunk) 之前所需要包含的最少数量的 chunks。数量必须大于等于2,或者少于等于 chunks的数量,传入 Infinity 会马上生成 公共chunk,但里面没有模块。

拆分公共资源

同 上面的拆分第三方库一样,拆分公共资源可以将公用的模块单独打出一个 chunk,你可以设置 minChunk 来选择是共用多少次模块才将它们抽离。配置如下:

new webpack.optimize.CommonsChunkPlugin({
 name: &#39;common&#39;,
 minChunks: 2,
}),
Copy after login

是否需要进行这一步优化可以自行根据项目的业务复用度来判断。

开启 gzip

使用 CompressionPlugin 插件开启 gzip 即可:

// 添加 gzip
new CompressionPlugin({
 asset: &#39;[path].gz[query]&#39;,
 algorithm: &#39;gzip&#39;,
 test: /\.(js|html)$/,
 threshold: 10240,
 minRatio: 0.8
})
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用Vue如何实现拦截器对token处理方法有哪些?

使用js和jQuery如何实现指定赋值方法

有关Vue中如何换肤?

The above is the detailed content of How to optimize packaging using React and Webpack?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React responsive design guide: How to achieve adaptive front-end layout effects React responsive design guide: How to achieve adaptive front-end layout effects Sep 26, 2023 am 11:34 AM

React Responsive Design Guide: How to Achieve Adaptive Front-end Layout Effects With the popularity of mobile devices and the increasing user demand for multi-screen experiences, responsive design has become one of the important considerations in modern front-end development. React, as one of the most popular front-end frameworks at present, provides a wealth of tools and components to help developers achieve adaptive layout effects. This article will share some guidelines and tips on implementing responsive design using React, and provide specific code examples for reference. Fle using React

React code debugging guide: How to quickly locate and solve front-end bugs React code debugging guide: How to quickly locate and solve front-end bugs Sep 26, 2023 pm 02:25 PM

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

See all articles