build
构建 UniApp 项目,支持多种构建目标(h5、mp-weixin、app-plus)。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.exec | ChildProcess['exec'] | 执行子进程命令 |
deps.join | Path['join'] | 路径拼接 |
deps.existsSync | FileSystem['existsSync'] | 检查文件是否存在 |
deps.setTimeout | typeof setTimeout | 超时函数 |
环境要求
- Node.js: 用于执行构建命令
- uni-cli: UniApp 命令行工具
bash
npm install -g @dcloudio/uni-cli函数签名
typescript
function build(
projectPath: string,
target: BuildTarget,
deps: UniBuildDeps,
options?: BuildOptions
): Promise<BuildResult>
type BuildTarget = 'h5' | 'mp-weixin' | 'app-plus'
interface BuildOptions {
useCustomScript?: boolean // 是否使用自定义构建脚本
customScript?: string // 自定义构建脚本名称
timeout?: number // 构建超时时间(毫秒)
}
interface BuildResult {
success: boolean
outputPath?: string
error?: string
logs: string[]
}参数
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
projectPath | string | 是 | - | 项目路径 |
target | BuildTarget | 是 | - | 构建目标(h5/mp-weixin/app-plus) |
deps | UniBuildDeps | 是 | - | 依赖注入对象 |
options.useCustomScript | boolean | 否 | false | 是否使用自定义构建脚本 |
options.customScript | string | 否 | 'build' | 自定义构建脚本名称 |
options.timeout | number | 否 | 300000 (5分钟) | 构建超时时间(毫秒) |
返回值
| 类型 | 说明 |
|---|---|
Promise<BuildResult> | Promise,解析为构建结果对象 |
工作原理
- 准备构建命令:
- 如果使用自定义脚本:执行
npm run ${customScript} - 否则:执行
npx uni build --platform ${target}
- 如果使用自定义脚本:执行
- 执行构建:使用
exec执行构建命令,捕获标准输出和错误输出 - 设置超时:如果构建时间超过
timeout,自动终止进程 - 检查输出目录:根据构建目标确定输出目录路径
h5:dist/build/h5mp-weixin:dist/build/mp-weixinapp-plus:dist/build/app
- 返回结果:包含成功状态、输出路径、错误信息和详细日志
支持自定义构建脚本和超时控制,适用于 CI/CD 自动化构建场景。