Skip to main content

前端 优化代码体积

当我使用npm run build的时候,项目构建了很久。所以考虑用create-react-app网站下面的工具来缩小代码体积

 Analyzing the Bundle Size

https://create-react-app.dev/docs/analyzing-the-bundle-size


更改完成后

npm run build

npm run analyze

可以看到以下的图片:

其中main.js有1.57mb


然后起服务

serve -s build -l 8000


进入到首页之后,打开network,查看js,发现main.js有500kb。这个500kb是已经用gzip压缩过了,但是却还有这么大。500*3=1500说明源文件有1.5mb左右


其中, antd占了25%, recharts占了13%, react-dom占了7.6%,dnd-kit占了2.8%

其中recharts用于统计页面,dnd-kit用于拖拽排序-编辑器页面。


所以在加载首页的时候,先不加载编辑页面和统计页面的js的话,体积会小很多。


路由懒加载

因为项目中,体积占比最大的是Edit和Stat页面(编辑和统计页面),所以考虑使用路由懒加载,拆分bundle,优化首页体积


router文件中,之前:

import Edit from "../pages/question/Edit";
import Stat from "../pages/question/Stat";

现在:

const Edit = lazy(() => import("../pages/question/Edit"));
const Stat = lazy(() => import("../pages/question/Stat"));

为了让生成的文件更加可读,可以改成下面这样:

const Edit = lazy(
() => import(/* webpackChunkName: "editPage" */ "../pages/question/Edit")
);
const Stat = lazy(
() => import(/* webpackChunkName: "statPage" */ "../pages/question/Stat")
);

再次使用:

npm run build

npm run analyze


发现main.js现在只有1.13mb,小了很多


然后再次运行 serve -s build -l 8000 

查看首页的js文件,相比于之前的500kb,现在只有360kb了。实际体积从1.57MB到1.15MB, 优化了26%。


那么接下来还剩下antd和react-dom。怎么继续拆分呢?


在第一次向服务端请求数据的时候


会传回诸如src, antd, react和其他第三方的库。其中,除了src,其他的库的版本是不太会变更的,除非更新。

那么第二次请求的时候,那些不变的就可以使用http缓存,只传更新了的src就行。


HTTP缓存

想要实现http缓存,需要用到webpack的知识

找到optimization.splitChunks这个配置


然后可以在项目中的craco.config.js中

加入webpack的配置

module.exports = {
webpack: {
configure(webpackConfig) {
if (webpackConfig.mode === "production") {
if (webpackConfig.optimization === null) {
webpackConfig.optimization = {};
}
webpackConfig.optimization.splitChunks = {
chunks: "all",
cacheGroups: {
antd: {
name: "antd-chunk",
test: /antd/, //路径
priority: 100, //优先级
},
reactDom: {
name: "reactDom-chunk",
test: /react-dom/,
priority: 99,
},
vendors: {
name: "vendors-chunk",
test: /node_modules/,
priority: 98,
},
},
};
}
return webpackConfig;
},
},
devServer: {
port: 8000,
proxy: {
"/api": "http://localhost:3001",
},
},
};

就能将antd, reactDom和vendors分成三个包, src也会成为一个包

运行npm run build


可以看到以上的结果,包都被拆分开了

查看网页上的network可以发现,在第一次访问的时候,main.js的包被压缩到了35kb。然后在第二次及之后的访问,都会返回304 not modified! 实现了缓存!大大提高了加载效率


CSS拆分

create-react-app会根据路由的懒加载自动拆分CSS文件

就不用我来自己做了








Comments

Popular posts from this blog

Valgrind

  Using Valgrind to check memory How to use Valgrind -To valgrind the program, run the valgrind command and give it our program name as an argument. -For example, if we want to run ./myProgram hello 42, we can simply run Valgrind ./myProgram hello 42.  Uninitialized Values -When we run the program, we may use uninitialized values. It needs to be fixed. Valgrind can tell us about the use of uninitialized values. But it only tell when the control flow of the program depends on the unitialized value. For example, uninitialized value appears in the conditional expression of an if, or a loop, or in the switch statement. -If we want to know where the uninitialized value is from, we can use Valgrind    --track-origins=yes ./myProgram -Using -fsanitize=address can find a lot of problems that Memcheck cannot.  -We can use Valgrind with GDB to debug. We can run: --vgdb=full --vgdb-error=0., then Valgrind will stop on the first error that it encounters and give control to ...

Error Handling and Exceptions

  Error Handling and Exceptions - The worst possible way to deal with any problem is for the program to produce the wrong answer without informing the user - a silent failure.  - When the program deals with an error by aborting, it should do so with the explicit intention of the programmer. (i.e. the programmer should call assert or check a condition then call abort) And the program should give an error message to the user. Simply segmentation fault due to an invalid memory access is never appropriate. - Sometimes we would prefer to handle the error more gracefully. Graceful error handling requires making the user aware of the problem, as well as allowing the program to continue to function normally. - For example, we would present the user with some options to remedy the situation, like entering a different input, select a different file, retry a failed operation, etc.  - As our programming skills develop, we should get into the practice of writing bullet proof code - co...

ADTs

  ADTs 1. Queue -FIFO We can implement in this way:  template<typename T> class Queue { public:     void enqueue(const T & item);     T dequeue();     T & peek()     const T & peek() const;     int numbebrOfItem() const; }; - In the actual C++ STL library, it has the following functions: push() pop() peek() 2. Stack - LIFO We can implement in this way: template<typename T> class Stack { public:     void push(const T & item);     T pop();     T & peek();     const T & peek() const;     int numberOfItem() const; }; In the C++ STL library, it has similar functions as queue. 3. Sets - Add - Test if an item is in the set - Check if the set is empty - Take the union of two set - intersect two sets A variant of this ADT is a multiset. (Also called a bag) It allows the same element to appear multiple times, whereas a true set either has an object or n...