import { build } from "vite"
import vue from "@vitejs/plugin-vue"
import vueJsx from "@vitejs/plugin-vue-jsx"
import path from "path"
import dts from "vite-plugin-dts"
import { replaceCodePlugin } from "vite-plugin-replace";
import { getOutput, getPath, getPkgs } from "@princess-ui/share";

export default function (name: string) {
    return build({
        logLevel: "error",
        resolve: {
            alias: {
                "@princess-ui": getPkgs(),
            }
        }, 
        plugins: [
            replaceCodePlugin({
                replacements: [
                //   {
                //     from: "@princess-ui/components",
                //     to: "../",
                //   },
                //   {
                //     from: /\@princess\-ui\/theme-chalk\/src\/(.*?)\.scss/i,
                //     to: "princess-ui/theme-chalk/$1.css"
                //   }
                ],
            }),
            vue({ isProduction: true }),
            vueJsx(),
            dts({
                tsConfigFilePath: getPath("tsconfig.json"),
                outputDir: getOutput("lib"),
                cleanVueFileName: true,
                include: ['all.ts', "hooks", "components"],
                staticImport: true,
            }),
        ],
        build: {
            outDir: getOutput("lib"),
            emptyOutDir: false,
            lib: {
                entry: getPkgs(`all.ts`),
                name: name,
                formats: ["es", "umd"],
                fileName: format => `index${format=='es'?'':'.umd'}.js`,
            },
            rollupOptions: {
                // 确保外部化处理那些你不想打包进库的依赖
                external: id => {
                    if (/^vue/.test(id)) {
                        return true
                    }
                    if (/^princess-ui/.test(id)) {
                        return true
                    }
                    return false
                },
                output: [
                    {
                        format: "es",
                        assetFileNames(chunkInfo) {
                            if (chunkInfo.name == "style.css") {
                                return `style.css`
                            }
                        },
                        globals: (id: string) => {
                            if (/^vue/.test(id)) {
                                return "Vue"
                            }
                        },
                    },
                    {
                        exports: "named",
                        format: "umd",
                        globals: (id: string) => {
                            if (/^vue/.test(id)) {
                                return "Vue"
                            }
                        },
                    },
                ],
            },
        },
    })
}