在 Vite (Rollup) 中分离 Material UI 作为手动 chunk 以减少 chunk 大小

Separating Material UI in Vite (Rollup) as a manual chunk to reduce chunk size

有人用 Vite 捆绑他们的 MUI 应用吗?我对来自 Vite/Rollup 的供应商块 (1.1MB) 有多大感到惊讶。我提出了以下配置,它将 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

有人知道这是怎么回事吗?我怀疑我没有正确摇树。

如果您为“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
}
},

如果你想保留所有模块试试这个

...
manualChunks: (id) => {
    if (id.includes('node_modules')) return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
...

此致