JavaScript/vite/组件构建:修订间差异
来自康健生活
| (未显示同一用户的11个中间版本) | |||
| 第1行: | 第1行: | ||
== 标题文本 == | == 标题文本 == | ||
组件打包也被称之为<code>库模式打包</code>。在配置文件中 build 属性下添加 lib 配置。 | |||
=== 忽略组件 === | |||
在打包过程中忽略被引用的组件(如 node_modules 中的组件),以便减少生成产物的体积。 | |||
<syntaxhighlight lang="javascript"> | |||
{ | |||
build: { | |||
rollupOptions: { | |||
external: ['vue', 'ant-design-vue'], | |||
}, | |||
}</syntaxhighlight> | |||
=== 全局变量 === | |||
在 UMD 构建模式下为这些外部化的依赖提供一个全局变量 | |||
<syntaxhighlight lang="javascript"> | |||
{ | |||
build: { | |||
rollupOptions: { | |||
output: { | |||
globals: { | |||
vue: 'Vue', | |||
}, | |||
}, | |||
}, | |||
}</syntaxhighlight> | |||
== 单组件构建 == | == 单组件构建 == | ||
== 多组件构建 == | == 多组件构建 == | ||
== 多文件单编译 == | == 多文件单编译 == | ||
设置输入文件的目录 | |||
{{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') | |||
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(path.join(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>}} | |||
执行 | |||
{{Shc_out|<syntaxhighlight lang="bash"> | |||
npm run bundle | |||
</syntaxhighlight>|<syntaxhighlight lang="bash"> | |||
npm warn config ignoring workspace config at /home/kwy/postlab-core/packages/postlab-platform/.npmrc | |||
> @postlab/platform@0.0.3 bundle | |||
> vite build --config=vite.config.bundle.ts | |||
vite v6.3.4 building for production... | |||
✓ 29 modules transformed. | |||
bundle/vite-envs.es.js 0.00 kB │ gzip: 0.02 kB | |||
// ... | |||
bundle/io/tauri/io.es.js 10.04 kB │ gzip: 3.31 kB | |||
bundle/vite-envs.cjs.js 0.01 kB │ gzip: 0.03 kB | |||
// ... | |||
bundle/io/tauri/io.cjs.js 3.90 kB │ gzip: 1.64 kB | |||
✓ built in 340ms | |||
</syntaxhighlight>|$|/home/kwy}} | |||
生成声明文件需要 vue-tsc 或 tsc 支持 | |||
{{hc|head=package.json|output=<syntaxhighlight lang="bash"> | |||
{ | |||
"scripts": { | |||
"dts": "vue-tsc --project ./tsconfig.bundle.json", | |||
"bundle": "vite build --config=vite.config.bundle.ts && npm run dts", | |||
// ... | |||
} | |||
</syntaxhighlight>}} | |||
需要额外注意的是 tsconfig.bundle.json 中 paths 与 rootDir 的设定 | |||
{{hc|head=tsconfig.bundle.json|output=<syntaxhighlight lang="bash"> | |||
{ | |||
"extends": "./tsconfig.json", | |||
"compilerOptions": { | |||
// 指定源文件的根目录 | |||
// 影响编译后输出文件的结构 | |||
// 不影响编译文件的选择 | |||
// 有助于组织源文件和输出文件的结构 | |||
"rootDir": "./src", | |||
// 设置用于解析非相对模块名称的基目录 | |||
// 简化模块导入,但不影响输出文件 | |||
// 仅影响非相对导入 | |||
// 简化了导入模块时的路径处理 | |||
"baseUrl": "./", | |||
// 在构建声明文件过程中忽略 paths 中的 "@postlab/types" | |||
// "@postlab/types" 将从 package.json 中的 "@postlab/types": "workspace:^" 引入 | |||
"paths": { | |||
"~/*": ["./src/*"] | |||
} | |||
} | |||
} | |||
</syntaxhighlight>}} | |||
== 单文件编译 == | |||
借助 terser 对多个单文件进行单独编译,与上文的多文件编译类似。但是这种方法较为繁琐,需要先通过 tsc 或 vue-tsc 生成编译产物 js 文件和声明文件,再通过 terser 将产物 js 文件二次处理。不推荐这种方式,留存仅为提供参考思路。 | |||
{{hc|head=vite.config.bundle.ts|output=<syntaxhighlight lang="bash"> | |||
import { defineConfig, type Plugin } from 'vite' | |||
import path from 'path' | |||
import * as glob from 'glob' | |||
import { resolve as node_resolve } from 'node:path' | |||
import viteBaseConfig from './vite-base-config' | |||
import { exec } from 'child_process' | |||
/** | |||
* 构建的流程 | |||
* 1. 执行组件的构建 vite.config.bundle.ts | |||
* 2. 零散文件的编译和声明 tsconfig.bundle.json | |||
* 3. terser 混淆压缩编译后的零散文件 | |||
*/ | |||
const testWritePlugin: Plugin = { | |||
name: 'test-generator', | |||
apply: 'build', | |||
closeBundle: (error?: Error) => { | |||
if (!error) { | |||
return new Promise((res, rej) => { | |||
exec('npm run dts', (err) => { | |||
if (err) rej(err) | |||
// 遍历文件下所有文件 | |||
const cup = glob.sync(path.resolve(__dirname, './bundle', 'packages/**/*.js')) | |||
const cup2 = glob.sync(path.resolve(__dirname, './bundle', 'src/**/*.js')) | |||
Promise.all( | |||
cup.concat(cup2).map((_) => { | |||
exec( | |||
`terser ${_} --compress ecma=2016,computed_props=false --module --mangle --output ${_}`, | |||
(e) => { | |||
if (e) rej(err) | |||
}, | |||
) | |||
}), | |||
) | |||
.then((_) => { | |||
res() | |||
}) | |||
.catch((e) => rej(e)) | |||
}) | |||
}) | |||
} | |||
}, | |||
} | |||
export default defineConfig({ | |||
plugins: [ | |||
...viteBaseConfig.plugins, | |||
testWritePlugin, | |||
], | |||
build: { | |||
// ... | |||
minify: 'esbuild', | |||
lib: { | |||
entry: { | |||
ci: node_resolve(__dirname, './src/components/index.ts'), | |||
}, | |||
name: 'ci', | |||
fileName: (format) => `index.${format}.js`, | |||
formats: ['es', 'cjs'], | |||
}, | |||
}, | |||
}) | |||
</syntaxhighlight>}} | |||
== tree shaking == | == tree shaking == | ||
在多组件或多文件的库中,保持此库支持 tree shaking 需要在 package.json 中设置 sideEffects。 | 在多组件或多文件的库中,保持此库支持 tree shaking 需要在 package.json 中设置 sideEffects。 | ||