/// import { defineConfig, type Plugin } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const here = path.dirname(fileURLToPath(import.meta.url)); const publicDir = path.resolve(here, '..', 'public'); // 与旧界面、服务端共用的 UMD 源文件。旧界面按经典脚本加载、服务端用 require;这里仅在构建时包一层: // 提供局部 module/require,让文件走自身的 CommonJS 分支,再把 module.exports 作为 ES 默认导出。源文件不改动。 const SHARED = new Set([ 'calculations.js', 'ledger-values.js', 'report-rules.js', 'recovery-rules.js', 'fee-estimates.js', 'credit-card-fees.js', 'order-formula.js', 'order-templates.js', 'order-copy.js', 'order-entry-model.js', ]); export function sharedUmd(): Plugin { return { name: 'ledger-shared-umd', enforce: 'pre', transform(code, id) { const file = id.split('?')[0]; if (path.dirname(file) !== publicDir || !SHARED.has(path.basename(file))) return null; const deps = [...new Set([...code.matchAll(/require\('\.\/([\w-]+)'\)/g)].map(match => match[1]))]; for (const dep of deps) if (!SHARED.has(dep + '.js')) this.error(`共用文件 ${path.basename(file)} 依赖了未列入的 ${dep}.js`); const header = deps.map((dep, i) => `import __shared${i} from './${dep}.js';\n`).join('') + `const __sharedDeps = {${deps.map((dep, i) => `'./${dep}': __shared${i}`).join(', ')}};\n` + 'const require = name => {\n' + ' if (!Object.prototype.hasOwnProperty.call(__sharedDeps, name)) throw new Error("未知依赖 " + name);\n' + ' return __sharedDeps[name];\n' + '};\n' + 'const module = { exports: {} };\n'; return { code: header + code + '\nexport default module.exports;\n', map: null }; }, }; } export default defineConfig({ base: '/next/', plugins: [sharedUmd(), react()], resolve: { alias: { '@public': publicDir } }, server: { fs: { allow: [here, publicDir] } }, build: { outDir: 'dist', emptyOutDir: true, modulePreload: { polyfill: false }, chunkSizeWarningLimit: 2000, rollupOptions: { output: { manualChunks(id) { if (/node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) return 'react'; if (/node_modules[\\/](antd|@ant-design|rc-[^\\/]+|@rc-component)[\\/]/.test(id)) return 'antd'; return undefined; }, }, }, }, test: { environment: 'jsdom', setupFiles: ['./test/setup.ts'], include: ['test/**/*.test.{ts,tsx}'], testTimeout: 20000, }, });