Webpack packaging optimization guide

Preface

At present, the code volume of all company projects is relatively large, and the packaged files will be very large, which may even lead to insufficient memory when packaging and compressing the code, and the page loading speed is also slow. To optimize loading speed, here are some coding guidelines:

1. Browser (chrome) operating indicators

  1. The number of concurrent browser requests chromeis6
  2. webpackThe purpose of optimization is to improve the loading speed of the first screen, that is, to ensure that users see the overall page frame first and reduce the white screen time.

2. Optimization method

1. webpack packaging

webpackReasonable splitting of files during packaging can be configured automatically 文件切割, and the maximum file size after cutting will not exceed 1MB. The main configuration contents are as follows:

module.exports = {
    
    
  /** 其他wenpack配置 */
  optimization: {
    
    
    splitChunks: {
    
    
      chunks: 'all',
      name: false,
      minSize: 600 * 1024,
      maxSize: 1000 * 1024
    }
  }
}
2. Lazy loading

The method used in the code 懒加载is to load the file. In webpack4, dynamically loading files import('xxx')can be used directly.

• It is recommended to perform lazy loading reactin the project路由层面
import React, {
    
     Suspense, lazy } from 'react'
import {
    
     HashRouter, Switch, Route } from 'react-router-dom'

export default function App() {
    
    
  return (
    <HashRouter>
      <Suspense fallback={
    
    <div>Loading...</div>}>
        <Switch>
          <Route path="/" component={
    
    lazy(() => import('./routes/Home'))} exact />
          <Route path="/settings" component={
    
    lazy(() => import('./routes/Settings'))} exact />
          <Route component={
    
    lazy(() => import('./routes/404'))} />
        </Switch>
      </Suspense>
    </HashRouter>
  )
}
• If a component has a very large amount of code, it can also 组件层面be loaded lazily in
import React, {
    
     Suspense } from 'react'

const OtherComponent = React.lazy(() => import('./OtherComponent'))
const AnotherComponent = React.lazy(() => import('./AnotherComponent'))

const MyComponent = () => (
  <div>
    <Suspense fallback={
    
    <div>Loading...</div>}>
      <section>
        <OtherComponent />
        <AnotherComponent />
      </section>
    </Suspense>
  </div>
)
动态加载Third party libraries
import React from 'react'

export default class SimpEditor extends React.Component {
    
    
  async componentDidMount() {
    
    
    // 由于simditor比较大,所以在组件挂在后再去加载
    // 加载过程中可添加相应的加载动画
    const Simditor = await import(/* webpackChunkName: "simditor" */ 'simditor')
  }
}
3. Resource file packaging.

Resource files include pictures, videos, audios, fonts and other files. url-loaderBe sure to pay attention to the configuration limitoptions when configuring

module.exports = {
    
    
  module: {
    
    
    rules: [
      {
    
    
        test: /\.(png|jpe?g|gif|webp)(\?.*)?$/,
        use: [
          {
    
    
            loader: 'url-loader',
            options: {
    
    
              limit: 8192 // 文件小于8k时,会被编译为base64,否则会以单独的文件的形式
            }
          }
        ]
      }
    ]
  }
}
- base64 encoding

It is usually about 33% larger than the original file, so when a large file is compiled into base64, the file size will become very large. Small files have little impact

- Preloading

Load the resources of the page to be accessed in the future in advance. When using code cutting, we can use preloading to load the resources that will be used later. Currently Chrome, Firefox, IE11all have some support. and are supported everest-cliby default , no additional configuration is requiredcssjsprefetch

<!-- prefetch使用方式 -->
<link href="./static/js/chunk-b2e731ba.c6d62f25.js" rel="prefetch" />
- Please be sure to remove unnecessary packages in the project

In some projects, packages that are not used in the page are still retained, resulting in very large files after packaging.

- For projects using everest-cli, you can use the command everest build -r to generate a packaging report file. In this file, we can view the packaged size of each module. With targeted optimization
- After packaging, try to ensure that the number of initial js in the html does not exceed 6, so that the browser can load it in parallel
-babel configuration

babelPlease try not to use the fields during configuration. @babel/preset-envWhen used , dynamically imported files will not be supported, resulting in a larger initial load file on the page.modulescjscjs

3. Optimization guidance:

  1. When the overall file size of the code cannot be reduced, try to reduce the number 减少首屏加载of files so that users can see the page as soon as possible and allow users to gradually load files during subsequent use.
  2. 合理拆分文件, try to ensure that the file sizes are not too different, and do not split too many files, causing the loading speed to be too slow.
  3. Cooperate with the backend Nginxto make reasonable use of it 静态资源的强缓存to speed up access efficiency.

Guess you like

Origin blog.csdn.net/weixin_55846296/article/details/131718501