JavaScript/vite/组件构建:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第104行: 第104行:


== 单文件编译 ==
== 单文件编译 ==
借助 terser 对多个单文件进行单独编译,与上文的多文件编译类似。
{{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。