JavaScript/vite/组件构建:修订间差异
来自康健生活
| 第3行: | 第3行: | ||
== 多组件构建 == | == 多组件构建 == | ||
== 多文件单编译 == | == 多文件单编译 == | ||
{{hc|head=vite.config.ts|output=<syntaxhighlight lang="bash"> | |||
import path from 'path' | |||
import * as glob from 'glob' | |||
import { fileURLToPath } from "url" | |||
const entries = new Map<string, string>() | |||
const GLOB_PATH = path.resolve(__dirname, 'src/**/*.ts') | |||
const OUTPUT_PATH = path.join(__dirname, 'bundle') | |||
for (const file of glob.sync(GLOB_PATH)) { | |||
const filenameWidthExt = file.split('/').at(-1) | |||
const filename = filenameWidthExt?.split('.')[0] | |||
if (!filename) continue; | |||
const absolutePath = file.slice(0, file.length - filenameWidthExt.length) | |||
const relativePath = absolutePath.replace(new RegExp(path.join(__dirname, 'src'),'g'),'') | |||
entries.set(`${relativePath}/${fileName}`, fileURLToPath(new URL(file, import.meta.url))) | |||
} | |||
// Add any additional entries | |||
entries.set('index', './src/index.ts') | |||
// in the defineConfig | |||
build: { | |||
lib: { | |||
entry: Object.fromEntries(entries), | |||
fileName: (format, entryName) => `${entryName}.${format}.js`, | |||
formats: ['es', 'cjs'], | |||
// fileName: '[name]' | |||
}, | |||
rollupOptions: { | |||
external: [], | |||
}, | |||
target: 'esnext', | |||
sourcemap: true, | |||
emptyOutDir: true, | |||
},</syntaxhighlight>}} | |||
== tree shaking == | == tree shaking == | ||
在多组件或多文件的库中,保持此库支持 tree shaking 需要在 package.json 中设置 sideEffects。 | 在多组件或多文件的库中,保持此库支持 tree shaking 需要在 package.json 中设置 sideEffects。 | ||