gpt4 book ai didi

reactjs - 如何代码拆分 webpack 的 vendor block ?

转载 作者:行者123 更新时间:2023-12-02 18:58:55 25 4
gpt4 key购买 nike

由于代码拆分,我有一个 webpack main.bundle.js 重量 287kb,但我的 vendor.js5mb 。当用户第一次访问该网站时,他将不得不下载 5.2mb,这太大了。

拆分 vendor 的正确方法是什么,以便用户只下载他需要运行页面的包,然后 webpack 在后台预取所有剩余的包?

我正在使用 webpack 4(我正在等待 Storybook 支持 webpack 5,然后再升级。如果 W5 中有新的方法,请告诉我)。

这是我的配置:

/* eslint-env node */
const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const Dotenv = require("dotenv-webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const isProductionMode = (mode) => mode === "production";

module.exports = () => {
const env = require("dotenv").config({ path: __dirname + "/.env" });
const nodeEnv = env.parsed.NODE_ENV;
return {
mode: "development",
entry: "./src/index.tsx",
output: {
path: path.join(__dirname, "./dist"),
filename: "[name].[hash].bundle.js",
publicPath: "/",
},
resolve: {
extensions: [".ts", ".tsx", ".js", "jsx", ".json"],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: { loader: "babel-loader" },
},
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.(png|jpg|jpeg|gif)$/, use: ["file-loader"] },
{
test: /\.svg$/,
use: [
{
loader: "babel-loader",
},
{
loader: "react-svg-loader",
options: {
jsx: true,
},
},
],
},
],
},
devServer: {
historyApiFallback: true,
port: 3000,
inline: true,
hot: true,
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
new Dotenv(),
],
optimization: {
minimize: isProductionMode(nodeEnv),
minimizer: isProductionMode(nodeEnv) ? [new TerserPlugin()] : [],
splitChunks: { chunks: "all" },
},
};
};

最佳答案

这有助于我拆分 vendor 包。

来源:https://gist.github.com/davidgilbertson/c9af3e583f95de03439adced007b47f1

splitChunks: {
chunks: 'all',
enforce: true,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`;
},
},
},
},

关于reactjs - 如何代码拆分 webpack 的 vendor block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65858859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com