【问题标题】:Separating Material UI in Vite (Rollup) as a manual chunk to reduce chunk size将 Vite (Rollup) 中的 Material UI 分离为手动块以减小块大小
【发布时间】:2021-10-09 02:44:57
【问题描述】:

是否有人使用 Vite 来捆绑他们的 MUI 应用程序?我很惊讶我的供应商块(1.1MB)来自 Vite/Rollup。我想出了下面的配置,它将 MUI 包分成自己的块:

import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
import { dependencies } from "./package.json";

// whenever you get the error: (!) Some chunks are larger than 500kb after minification
// find the biggest lib in your vendors chunk and add it to bigLibs
const bigLibs = [
  { regExp: /^@material-ui*/, chunkName: "@material-ui" },
  { regExp: /^@aws-amplify*/, chunkName: "@aws-amplify" },
];

function getManualChunks(deps: Record<string, string>) {
  return Object.keys(deps).reduce(
    (prev, cur) => {
      let isBigLib = false;
      for (const l of bigLibs) {
        if (l.regExp.test(cur)) {
          isBigLib = true;
          if (prev[l.chunkName]) {
            prev[l.chunkName].push(cur);
          } else {
            prev[l.chunkName] = [cur];
          }
          break;
        }
      }
      if (!isBigLib) prev.vendors.push(cur);
      return prev;
    },
    { vendors: [] } as Record<string, string[]>
  );
}

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: getManualChunks(dependencies),
      },
    },
  },
  plugins: [reactRefresh()],
  resolve: {
    alias: [
      {
        find: "./runtimeConfig",
        replacement: "./runtimeConfig.browser",
      },
    ],
  },
});

但是...我在浏览器中遇到错误:

@material-ui.1d552186.js:1 Uncaught TypeError: Cannot read property 'exports' of undefined
    at @material-ui.1d552186.js:1

有人知道发生了什么吗?我怀疑我没有正确地摇树。

【问题讨论】:

    标签: reactjs material-ui rollup vite


    【解决方案1】:

    如果你为“manualChunks”设置了一个函数,第一个参数将是一个“字符串”

    https://www.rollupjs.org/guide/en/#outputmanualchunks

    试试这个:

    manualChunks: (id) => {
    if (id.includes("node_modules")) {
        if (id.includes("@aws-amplify")) {
            return "vendor_aws";
        } else if (id.includes("@material-ui")) {
            return "vendor_mui";
        }
    
        return "vendor"; // all other package goes here
    }
    },
    

    【讨论】:

    • 我最终仍然有非常大的块,但这是因为这些库太大了。这是修复错误的正确答案。谢谢!
    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2022-08-06
    • 1970-01-01
    • 2022-12-08
    • 2015-02-07
    • 2021-12-23
    相关资源
    最近更新 更多