react-打包和本地预览 ——打包优化
项目打包
打包指的是将项目中的源代码和资源文件进行处理,生成可在生产环境中运行的静态文件的过程
打包命令
npm run build
本地预览
本地预览是指在本地通过静态服务器模拟生产服务器运行项目的过程
安装本地服务包
npm i -g serve
启动
serve -s build
浏览器访问生成的本地地址 一般是3000端口
http://localhost:3000/
打包优化
路由懒加载
什么是路由懒加载?
路由懒加载是指路由的JS资源只有在被访问的时候才会动态获取,目的是为了优化项目首次打开的时间
配置路由懒加载
- 把路由修改为由React提供的lazy函数进行动态导入
- 使用React内置的Suspense组件包裹路由中element选项对应的组件
lazy函数进行动态导入
// 格式
const 命名 = lazy(()=>import('路径'))const Month = lazy(()=>import('@/page/Month/index'))
Suspense组件包裹路由组件
const router = createBrowserRouter([{path: "/",element: <Suspense> <Layout/></Suspense>,children: [{path: "/year",element:<Suspense><Year/></Suspense>,},{index:true,element: <Suspense><Month/></Suspense> ,},],}
])
包体积分享
什么是包体积分析
通过可视化的方式,直观的体现项目中各种包打包之后的体积大小方便做优化
实现
- 安装包 通过 source-map-explorer
- 配置命令指定要分析的js文件
安装
npm i source-map-explorer
配置命令指定要分析的js文件
"scripts": {"start": "craco start","build": "craco build","server": "json-server ./mock/home.json --port 3005","explorer": "source-map-explorer 'build/static/js/*.js'" //分析命令},
运行命令
npm run explorer
运行成功会自动在浏览器打开分析图
CDN优化
什么是CDN?
CDN是一种内容分发网络服务,当用户请求网站内容时,有离用户最近的服务器将缓存资源内容传递给用户
哪些资源可以放到CDN服务器?
体积较大的非业务JS文件,比如react,react-dom
- 体积较大,需要利用CDN文件在浏览器的缓存特性,加快加载时间
- 非业务JS文件,不需要经常做变动,CDN不用频繁更新缓存
项目中怎么实现 ?
- 把需要做CDN缓存的文件排除在打包之外(react,react-dom)
- 以CDN的方式重新引入资源(react,react-dom)
通过 craco 来修改 webpack 配置,从而实现 CDN 优化
craco.config.js 中:
const path = require('path')module.exports = {webpack:{alias:{'@':path.resolve(__dirname,'src')},configure: (webpackConfig) => {let cdn = {js: [],css: []}// 对webpack进行配置whenProd(() => {// 只会在生产环境执行webpackConfig.externals = {react: 'React','react-dom': 'ReactDOM',redux: 'Redux',}cdn = {js: ['https://cdn.bootcdn.net/ajax/libs/react/17.0.2/umd/react.production.min.js','https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js','https://cdn.bootcdn.net/ajax/libs/redux/4.1.0/redux.min.js'],css: []}})const { isFound, match } = getPlugin(webpackConfig,pluginByName('HtmlWebpackPlugin'))if (isFound) {// 找到了html的插件match.options.cdn = cdn}return webpackConfig}}
}
public/index.html 中:
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8" /><link rel="icon" href="%PUBLIC_URL%/favicon.ico" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="theme-color" content="#000000" /><metaname="description"content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /><!--manifest.json provides metadata used when your web app is installed on auser's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/--><link rel="manifest" href="%PUBLIC_URL%/manifest.json" /><!--Notice the use of %PUBLIC_URL% in the tags above.It will be replaced with the URL of the `public` folder during the build.Only files inside the `public` folder can be referenced from the HTML.Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" willwork correctly both with client-side routing and a non-root public URL.Learn how to configure a non-root public URL by running `npm run build`.--><title>React App</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><!-- 动态插入cdn资源 --><% htmlWebpackPlugin.options.cdn.css.forEach(cdnURL => { %><link rel="stylesheet" href="<%= cdnURL %>"></link><% }) %><!--This HTML file is a template.If you open it directly in the browser, you will see an empty page.You can add webfonts, meta tags, or analytics to this file.The build step will place the bundled scripts into the <body> tag.To begin the development, run `npm start` or `yarn start`.To create a production bundle, use `npm run build` or `yarn build`.--></body>
</html>