73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
import * as path from 'path';
|
||
import { defineConfig, UserConfig } from 'vite';
|
||
const packageJson = require('./package.json');
|
||
|
||
/**
|
||
* 生成 IIFE 配置的工厂函数
|
||
* @param platform 'desktop' | 'mobile'
|
||
*/
|
||
function createIIFEConfig(platform: 'desktop' | 'mobile'): UserConfig {
|
||
// 判断是否为生产环境构建
|
||
const isProd = process.env.BUILD_MODE === 'production';
|
||
|
||
return {
|
||
resolve: {
|
||
alias: {
|
||
'@': path.resolve(__dirname, 'src'),
|
||
},
|
||
},
|
||
define: {
|
||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||
'process.env': JSON.stringify({}),
|
||
global: 'window',
|
||
},
|
||
build: {
|
||
target: 'es2022',
|
||
lib: {
|
||
entry: path.resolve(__dirname, `src/js/${platform}.ts`),
|
||
name: `${packageJson.name.replaceAll('-', '_')}_${platform}_iife`,
|
||
formats: ['iife'],
|
||
fileName: () => `${platform}.js`,
|
||
},
|
||
rollupOptions: {
|
||
external: ['kintone'], // kintone 是网站提供的 api,需要处理
|
||
output: {
|
||
globals: {
|
||
kintone: 'kintone',
|
||
},
|
||
},
|
||
},
|
||
outDir: path.resolve(__dirname, `dist-iife/${platform}`), // 输出到 dist-iife 目录
|
||
sourcemap: isProd ? false : 'inline', // 生产环境关闭,开发环境使用 inline
|
||
minify: 'terser', // 强制进行混淆,避免全局变量被污染的问题
|
||
...(isProd && {
|
||
terserOptions: {
|
||
compress: {
|
||
drop_console: true, // 移除 console
|
||
drop_debugger: true, // 移除 debugger
|
||
pure_funcs: ['console.log'], // 移除 console.log
|
||
},
|
||
mangle: {
|
||
toplevel: true, // 混淆顶级作用域的变量名
|
||
},
|
||
format: {
|
||
comments: false, // 移除注释
|
||
},
|
||
},
|
||
}),
|
||
},
|
||
};
|
||
}
|
||
|
||
// 根据环境变量决定构建哪个平台
|
||
const platform = process.env.PLATFORM as 'desktop' | 'mobile';
|
||
|
||
if (!platform || !['desktop', 'mobile'].includes(platform)) {
|
||
throw new Error('Please specify PLATFORM environment variable: desktop or mobile');
|
||
}
|
||
|
||
/**
|
||
* 统一的 IIFE 构建配置
|
||
* 用于将 desktop.ts 和 mobile.ts 打包为 IIFE 格式
|
||
*/
|
||
export default defineConfig(createIIFEConfig(platform)); |