ossPlugin.ts 1.31 KB
import { parse, resolve } from 'path'
import { copyFileSync, existsSync, mkdirSync } from 'fs'
import type { Plugin } from 'vite'

interface OssPluginParamsType {
  enableOss?: boolean
}
export function OssPlugin({ enableOss }: OssPluginParamsType): Plugin {
  const name = 'vite-plugin-things-kit-oss-file-copy'
  return {
    name,
    apply: 'build',
    enforce: 'post',
    closeBundle() {
      if (!enableOss) return
      try {
        const needCopyFilePathList = [
          resolve(process.cwd(), './public/webapp/js/app.min.js'),
          resolve(process.cwd(), './public/webapp/js/stencils.min.js'),
          resolve(process.cwd(), './public/webapp/js/extensions.min.js'),
        ]
        const outputDirPath = resolve(process.cwd(), './dist/oss')

        if (!existsSync(outputDirPath))
          mkdirSync(outputDirPath)

        for (const item of needCopyFilePathList) {
          const { name, ext } = parse(item)
          copyFileSync(item, `${outputDirPath}/${name}${ext}`)
        }

        // eslint-disable-next-line no-console
        console.log(`\x1B[36m${name}\x1B[0m:\x1B[32m generate oss file success. \x1B[0m`)
      }
      catch (error) {
        // eslint-disable-next-line no-console
        console.log(`\x1B[36m${name}\x1B[0m:\x1B[31m generate oss file fail: ${error} \x1B[0m`)
      }
    },
  }
}