hooks 让它在 dev、build 前后执行自定义逻辑。
配置
unh.config.ts
import { defineConfig } from '@uni-helper/unh'
export default defineConfig({
hooks: {
// prepare 阶段执行
prepare() {
console.log('prepare')
},
// 开发前执行
dev({ platform, options, envData }) {
console.log('dev:', platform, options, envData)
},
// 开发后执行,只会执行一次
onDevAfter({ platform, options, envData }) {
console.log('devAfter:', platform, options, envData)
},
// 构建前执行
build({ platform, options, envData }) {
console.log('build:', platform, options, envData)
},
// 构建后执行
onBuildAfter({ platform, options, envData }) {
console.log('buildAfter:', platform, options, envData)
},
},
})
执行时机
| hook | 执行时机 |
|---|---|
prepare | unh prepare 调用时,也适合放进 package.json 的 prepare 脚本 |
dev | 执行 uni dev 之前 |
onDevAfter | uni dev 输出 ready in 之后,只执行一次 |
build | 执行 uni build 之前 |
onBuildAfter | uni build 结束之后 |
参数
prepare
() => void | Promise<void>
不接收参数
dev
(options: HookOptions) => void | Promise<void>
开发前执行
onDevAfter
(options: HookOptions) => void | Promise<void>
开发后执行,只会执行一次
build
(options: HookOptions) => void | Promise<void>
构建前执行
onBuildAfter
(options: HookOptions) => void | Promise<void>
构建后执行
interface HookOptions {
/** 当前编译平台 */
platform?: Platform
/** 编译命令行参数 */
options?: Record<string, any>
/** 当前编译环境变量,需要开启 env 配置才有该数据 */
envData?: Record<string, string>
}
三个字段都是可选的。envData 只在 env 配置开启时才有值。
示例
在构建前检查环境变量是否齐全:
unh.config.ts
import process from 'node:process'
import { defineConfig } from '@uni-helper/unh'
export default defineConfig({
env: true,
hooks: {
build({ platform, envData }) {
if (!envData?.VITE_API_BASE_URL) {
throw new Error(`缺少 VITE_API_BASE_URL,平台 ${platform}`)
}
},
},
})
hook 抛出错误时,进程打印 Fatal error: 并以退出码 1 结束,uni 命令不会执行。