前后端分离系列-chunk

2020-01-22  本文已影响0人  汤姆猫_6074

demo https://github.com/757566833/webpack-guide

在加入缓存之后,我们仅仅是让第二次加载及其以后,进行了快速响应
但是第一次加载还是巨慢,怎么办?

image.png 一般情况下,在开发项目的过程中,代码一直变化,但是第三方包是不会有变动的 image.png

例如 app的版本1 版本2 版本3 甚至app2都在依赖同一个react,antd版本

这样我们将打包的文件拆开 拆成react,antd,app 三大部分
webpack.prod.ts


import path from "path";
import webpack from "webpack";
import {BundleAnalyzerPlugin} from "webpack-bundle-analyzer";
import merge from "webpack-merge";
import common from "./webpack.common";
const config: webpack.Configuration = merge(common, {
    mode: "production",
    devtool: "source-map",
    optimization: {
        splitChunks: {
            chunks: "all",     
// 
            minSize: 100000, 
            maxSize: 300000,
            minChunks:1,
            cacheGroups: {
                react: {
                    test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
                    name: "react",
                    chunks: "all",
                },
                antd: {
                    test: /[\\/]node_modules[\\/]antd|\@ant(.+?)[\\/]/,
                    name: "antd",
                    chunks: "all",
                },
            },
        },
    },
    output: {
// 改成了chunk命名,避免出现0123这种
        filename: "[name].[hash].js",
        path: path.resolve(__dirname, "..", "dist"),
    },
    plugins: [
        new BundleAnalyzerPlugin(),
    ],
});

export default config;

这样拆完,build之后


image.png

但是有引申出来一个新问题,每次我只是改了js,并没有改css,所有的文件都会重新命名,这就造成了资源浪费
webpack的hash 分三种 hash chunkhash contenthash
webpack.common.ts

...
 plugins: [
        new HtmlWebpackPlugin({
            title: "test",
           template: path.resolve(__dirname,'template.html'),
        }),
        new MiniCssExtractPlugin({
            filename: "[name].[contenthash].css",
        }),

    ],
...

webpack.prod.ts

...
 output: {
        filename: "[name].[chunkhash].js",
        path: path.resolve(__dirname, "..", "dist"),
    },
...

具体的三种hash 自己搜一下,网上说的挺全的

上一篇下一篇

猜你喜欢

热点阅读