如何告诉 Vite 从构建中排除目录中的文件子集?

bai*_*idz 10 javascript rollup vue.js vite

我使用创建了一个新的 Vue 应用程序npm create vue。在运行时,该应用程序会获取配置并从中读取字符串。该字符串表示要在应用程序内呈现的组件的名称。这些动态组件位于“可插入”目录中

\n
.\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 App.vue\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 pluggables\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 ThisFoo.vue\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 ThatBar.vue\n
Run Code Online (Sandbox Code Playgroud)\n

所以基本上 App.vue 文件的作用是

\n
<script setup lang="ts">\nimport { onMounted, shallowRef, defineAsyncComponent } from "vue";\n\nconst pluggableComponent = shallowRef();\n\nonMounted(() => {\n  // fetch configuration\n  const componentName = "ThisFoo"; // extract from configuration\n\n  pluggableComponent.value = defineAsyncComponent(() => import(`./pluggables/${componentName}.vue`));\n});\n</script>\n\n<template>\n  <div>Pluggable below:</div>\n  <component :is="pluggableComponent" />\n</template>\n
Run Code Online (Sandbox Code Playgroud)\n

我可以在构建时访问配置文件,并知道运行时需要哪些组件,以及根据此配置将哪些组件视为“死代码”。有没有办法告诉 Vite 从构建中排除未使用的组件?

\n

例如,排除整个可插拔目录,但包括可插拔目录中所需的组件

\n
\n

vite build --exclude ./src/pluggables/** --include ./src/pluggables/ThisFoo.vue

\n
\n

或者通过创建自定义 Vite 构建函数,我可以在 CI/CD 期间调用并传入组件名称数组。

\n

Dua*_*nnx 13

要从构建过程中排除某些文件,您可以使用Rollup 的外部配置将它们标记为外部文件

// vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import * as path from "path";
import { fileURLToPath } from "node:url";

const filesNeedToExclude = ["src/pluggables/Comp1.vue", "src/pluggables/Comp2.vue"];

const filesPathToExclude = filesNeedToExclude.map((src) => {
  return fileURLToPath(new URL(src, import.meta.url));
});

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },

  build: {
    manifest: true,
    rollupOptions: {
      external: [
        ...filesPathToExclude
      ],
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

  • 我假设这个答案在捆绑库时不起作用,对吗?这对我不起作用。 (3认同)