将Vite(Rollup)中的Material UI分离为手动块,以减少块大小

Ben*_*ley 15 rollup reactjs material-ui vite

有人使用 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",
      },
    ],
  },
});
Run Code Online (Sandbox Code Playgroud)

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

@material-ui.1d552186.js:1 Uncaught TypeError: Cannot read property 'exports' of undefined
    at @material-ui.1d552186.js:1
Run Code Online (Sandbox Code Playgroud)

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

Tam*_*ona 27

如果您为“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
}
},
Run Code Online (Sandbox Code Playgroud)