1.路由懒加载:
(1)说明
路由懒加载是指路由的JS资源只有在被访问的时候才会被动态获取,是为了优化项目首次打开的时间。
(2)配置
- 把路由修改为由React提供的lazy函数进行动态导入
import {Suspense, lazy} from 'react' //lazy函数对组件进行导入 const Board = lazy(()=>import('@/page/Board')) const About = lazy(()=>import('@/page/About'))
- 使用React内置的Suspense组件包裹路由中的element选项对应的组件
const router = createBrowserRouter([ { path : '/', element : <Layout></Layout>, children :[{ index:true, element : <Suspense fallback={'load'}><Board></Board></Suspense> }, { path : '/about', element : <Suspense fallback={'load'}><About></About></Suspense> }] }, ])
2.包体积可视化分析
(1)下载依赖包
npm i source-map-explorer
(2)配置命令 package.json
"scripts": { "start": "craco start", "build": "craco build", "test": "react-scripts test", "eject": "react-scripts eject", "analyze" : "source-map-explorer 'build/static/js/*.js'" },
3.CDN优化
(1)说明:CDN是一种内容分发网络服务,当用户请求网站内容时,由离用户最近的服务器将缓存的资源内容传递给用户
(2)哪些资源可以放到CDN服务器?
- 体积比较大的非业务JS 文件,比如react、react-dom,需要利用CDN文件在浏览器的缓存特性,加快加载时间
- 非业务JS,不需要经常做变动,CDN不用频繁更新
(3)优化操作
- 把需要做CDN缓存的文件排除在打包之外
- 以CDN的方式重新引入资源
const path = require('path') const {whenProd,getPlugin,pluginByName} = require('@craco/craco') // const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { webpack : { alias : { //别名配置 '@' : path.resolve(__dirname,'src') } }, //配置webpack configure : (webpackConfig)=>{ let cdn; whenProd(()=>{ webpackConfig.externals = { react : 'React', 'react-dom' : 'ReactDOM' } cdn = { js : [ 'https://unpkg.com/react@latest/umd/react.development.js', 'https://unpkg.com/react-dom@latest/umd/react-dom.development.js' ] } }) const {isFound,match} = getPlugin( webpackConfig, pluginByName('HtmlWebpackPlugin') ) if(isFound) { match.userOptions.cdn = cdn } return webpackConfig } }
标签:react,lazy,const,CDN,js,React,path,优化,打包 From: https://www.cnblogs.com/qinlinkun/p/18073562