NX工作区CircleCI执行yarn install报endsWith属性undefined错误
NX工作区CircleCI执行yarn install报
Cannot read properties of undefined (reading 'endsWith')排查方案 错误复现场景
在面向React应用的NX工作区配置CircleCI流水线时,yarn install步骤执行失败,错误详情:
错误涉及路径:
/home/circleci/project/node_modules/@nrwl/js/node_modules/nx、/home/circleci/project/node_modules/@nrwl/remix/node_modules/nx
命令执行失败,退出码:1,执行命令:node ./bin/init
执行目录:/home/circleci/project/node_modules/@nrwl/js/node_modules/nx
输出内容:NX Cannot read properties of undefined (reading 'endsWith'),进程最终以退出状态码1终止。
当前使用的CircleCI配置如下:
version: 2.1 orbs: nx: nrwl/nx@1.4.0 jobs: agent: resource_class: xlarge docker: - image: cimg/node:lts-browsers parameters: ordinal: type: integer steps: - checkout - run: name: Install dependencies command: | yarn install - run: name: Start the agent << parameters.ordinal >> command: yarn nx-cloud start-agent no_output_timeout: 60m main: resource_class: xlarge docker: - image: cimg/node:lts-browsers environment: NX_CLOUD_DISTRIBUTED_EXECUTION: 'true' steps: - checkout - run: name: Install dependencies command: | yarn install - nx/set-shas: main-branch-name: 'main' - run: name: Initialize the Nx Cloud distributed CI run command: yarn nx-cloud start-ci-run - run: name: Run workspace lint command: yarn nx-cloud record -- yarn nx workspace-lint - run: name: Check format command: yarn nx-cloud record -- yarn nx format:check --base=$NX_BASE --head=$NX_HEAD - run: name: Run lint command: yarn nx affected --base=$NX_BASE --head=$NX_HEAD --target=lint --parallel=3 - run: name: Run test command: yarn nx affected --base=$NX_BASE --head=$NX_HEAD --target=test --parallel=3 --ci --code-coverage - run: name: Run build command: yarn nx affected --base=$NX_BASE --head=$NX_HEAD --target=build --parallel=3 - run: name: Stop all agents command: yarn nx-cloud stop-all-agents when: always workflows: version: 2 ci: jobs: - agent: name: Nx Cloud Agent << matrix.ordinal >> matrix: parameters: ordinal: [1, 2, 3] - main: name: Nx Cloud Main
根因说明
这个报错是NX生态里的常见版本兼容问题:@nrwl/js、@nrwl/remix等官方插件包嵌套安装了和工作区根目录版本不一致的nx包,嵌套版本的nx执行init初始化脚本时,读取路径相关参数拿到undefined值,调用endsWith方法时直接抛出异常,中断安装流程。
排查解决步骤
- 第一步先做本地版本校验:在本地项目根目录执行
yarn list nx,查看所有依赖层级下的nx版本号,如果子包嵌套的nx版本和根目录package.json中声明的nx主版本不一致,就可以确定是版本错配问题。 - 方案一:用Yarn的resolutions字段强制全工作区使用统一版本的nx。在根目录
package.json中添加如下配置,版本号替换为本地根目录安装的nx精确版本:
{ "resolutions": { "nx": "对应精确版本号,例如16.8.1" } }
配置完成后删除本地node_modules文件夹和yarn.lock文件,重新执行yarn install验证本地安装无报错后,再提交代码触发CI流水线。
- 方案二:全量对齐@nrwl生态包版本。执行
yarn nx migrate latest按照官方迁移脚本指引,把所有@nrwl/*开头的依赖包升级到和nx主版本完全匹配的版本,迁移完成后清理依赖缓存重装即可。 - CI配置补全:当前配置缺少依赖缓存和锁文件校验步骤,建议在install步骤前增加
yarn.lock存在性校验,同时配置CircleCI的node_modules缓存策略,避免CI环境每次安装时拉取到版本漂移的依赖包。 - 兼容处理:当前使用的
nrwl/nx@1.4.0orb版本发布时间较早,如果完成版本对齐后CI仍有异常,可以升级nx orb到最新稳定版,旧版orb的环境变量传递逻辑在高版本NX上存在兼容问题,也会间接触发nx初始化脚本异常。
内容的提问来源于stack exchange,提问作者Mark James
相关产品推荐
相关产品推荐

