拆分Dangerfile为多个子模块时提示导入danger模块错误如何解决?
问题根因
Danger 只会预处理入口 Dangerfile 中的danger相关导入语句,在执行前将其替换为全局注入的DSL对象,拆分后的子模块不会经过该预处理逻辑,因此子模块中直接导入danger包会触发报错。
修复步骤
1. 移除所有子模块中danger相关的导入语句
删除variable.ts、other.ts中对danger、danger-plugin-toolbox、danger-plugin-mentor的导入声明,这类依赖的导出对象都会被Danger自动注入到全局运行时,可直接调用。
2. 补充TypeScript类型声明(TS项目可选,JS项目可跳过)
在子模块目录下新增global.d.ts文件,声明全局可用的Danger相关变量,避免TS语法报错:
declare const danger: import('danger').DangerDSL; declare const committedFiles: import('danger-plugin-toolbox').committedFiles; declare const inCommit: import('danger-plugin-toolbox').inCommit; declare const prTitle: import('danger-plugin-toolbox').prTitle; declare const linkToSourceRepo: import('danger-plugin-toolbox').linkToSourceRepo; declare const mentor: import('danger-plugin-mentor').default;
3. 调整变量计算逻辑,避免顶层作用域直接调用DSL
原variable.ts中的变量在模块导入时就会执行计算,此时全局DSL还未完全注入,需要封装为函数在运行时调用才会生效,修改后的variable.ts代码如下:
// ./dangerjs/variable.ts export function getDangerVariables() { // 基础配置 const packageChanged: boolean = inCommit('package.json'); const lockfileChanged: boolean = inCommit('yarn.lock'); const npmLockfile: boolean = inCommit('package-lock.json'); const allFilesLen: number = committedFiles.length; const isWIP: boolean = prTitle.includes('[WIP]'); const isSkipped: boolean = prTitle.includes('[SKIP]'); const isSkipDanger: boolean = prTitle.includes('[SKIP-DANGER]'); const { assignees } = danger.github.pr; // 分支相关配置 const targetBranch = danger.github.pr.base.ref; const headBranch = danger.github.pr.head.ref; const isMergeRefMaster = targetBranch === 'master'; const isMergeRefProd = targetBranch === 'production'; const isMergeHeadDev = headBranch === 'dev'; const isMergeHeadMaster = headBranch === 'master'; const isGoingToProd = isMergeRefProd && isMergeHeadMaster; return { packageChanged, lockfileChanged, npmLockfile, allFilesLen, isWIP, isSkipped, isSkipDanger, assignees, targetBranch, headBranch, isMergeRefMaster, isMergeRefProd, isMergeHeadDev, isMergeHeadMaster, isGoingToProd } }
4. 调整校验逻辑代码
修改other.ts代码,在函数执行时再获取变量,直接使用全局注入的mentor方法:
// ./dangerjs/checks/other.ts import { getDangerVariables } from '../variables'; export function OtherChecks() { const { isGoingToProd, isSkipDanger } = getDangerVariables(); if (!isSkipDanger && !isGoingToProd) { mentor(); } }
5. 入口文件无需修改
原入口DANGERFILE.TS的逻辑保持不变即可,Danger会自动处理入口文件的依赖加载逻辑。
内容的提问来源于stack exchange,提问作者the_bluescreen
相关产品推荐
相关产品推荐

