nx-import
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesename: nx-import
description: Import, merge, or combine repositories into an Nx workspace using nx import. USE WHEN the user asks to adopt Nx across repos, move projects into a monorepo, or bring code/history from another repository.
name: nx-import
description: 使用nx import将代码仓库导入、合并或整合到Nx工作区中。适用于用户需要在多仓库中采用Nx、将项目迁移到单体仓库(monorepo),或从其他仓库引入代码/提交历史的场景。
Quick Start
快速开始
- brings code from a source repository or folder into the current workspace, preserving commit history.
nx import - After nx ,
22.6.0responds with .ndjson outputs and follow-up questions. For earlier versions, always run withnx importand specify all flags directly.--no-interactive - Run for available options.
nx import --help - Make sure the destination directory is empty before importing.
EXAMPLE: target has and
libs/utils; source haslibs/modelsandlibs/ui— you cannot importlibs/data-accessintolibs/directly. Import each source library individually.libs/
Primary docs:
- https://nx.dev/docs/guides/adopting-nx/import-project
- https://nx.dev/docs/guides/adopting-nx/preserving-git-histories
Read the nx docs if you have the tools for it.
- 可将源仓库或文件夹中的代码引入当前工作区,同时保留提交历史。
nx import - 在Nx 22.6.0版本之后,会返回.ndjson格式的输出并提出后续问题。对于更早的版本,请始终使用
nx import参数运行,并直接指定所有必要的标志。--no-interactive - 运行查看可用选项。
nx import --help - 导入前请确保目标目录为空。
示例:目标目录包含和
libs/utils;源目录包含libs/models和libs/ui——不能直接将libs/data-access导入到libs/中。请分别导入每个源库。libs/
主要文档:
- https://nx.dev/docs/guides/adopting-nx/import-project
- https://nx.dev/docs/guides/adopting-nx/preserving-git-histories
如果有条件,请阅读Nx官方文档。
Import Strategy
导入策略
Subdirectory-at-a-time ():
nx import <source> apps --source=apps- Recommended for monorepo sources — files land at top level, no redundant config
- Caveats: multiple import commands (separate merge commits each); dest must not have conflicting directories; root configs (deps, plugins, targetDefaults) not imported
- Directory conflicts: Import into alternate-named dir (e.g. ), then rename
imported-apps/
Whole repo ():
nx import <source> imported --source=.- Only for non-monorepo sources (single-project repos)
- For monorepos, creates messy nested config (,
imported/nx.json, etc.)imported/tsconfig.base.json - If you must: keep imported (projects extend it), prefix workspace globs and executor paths
tsconfig.base.json
逐个子目录导入():
nx import <source> apps --source=apps- 推荐用于单体仓库源——文件将直接放在顶层目录,无冗余配置
- 注意事项:需要执行多次导入命令(每次导入对应单独的合并提交);目标目录不能存在冲突的目录;不会导入根目录配置(依赖、插件、targetDefaults)
- 目录冲突处理:导入到重命名后的目录(例如),之后再进行重命名
imported-apps/
整个仓库导入():
nx import <source> imported --source=.- 仅适用于非单体仓库源(单项目仓库)
- 若用于单体仓库,会产生混乱的嵌套配置(、
imported/nx.json等)imported/tsconfig.base.json - 若必须使用:保留导入的(项目会继承该配置),为工作区通配符和执行器路径添加前缀
tsconfig.base.json
Directory Conventions
目录约定
- Always prefer the destination's existing conventions. Source uses but dest uses
libs/? Import intopackages/(packages/).nx import <source> packages/foo --source=libs/foo - If dest has no convention (empty workspace), ask the user.
- 始终优先遵循目标目录的现有约定。如果源目录使用而目标目录使用
libs/?请导入到packages/(packages/)。nx import <source> packages/foo --source=libs/foo - 如果目标目录没有约定(空工作区),请询问用户。
Common Issues
常见问题
pnpm Workspace Globs (Critical)
pnpm工作区通配符(关键)
nx importappspnpm-workspace.yamlCannot find moduleFix: Replace with proper globs from the source config (e.g. , ), then .
apps/*libs/shared/*pnpm installnx importappspnpm-workspace.yamlCannot find module修复方法:使用源配置中的正确通配符替换(例如、),然后执行。
apps/*libs/shared/*pnpm installRoot Dependencies and Config Not Imported (Critical)
根目录依赖与配置未导入(关键)
nx import- /
dependenciesfromdevDependenciespackage.json - from
targetDefaults(e.g.nx.json— critical for build ordering)"@nx/esbuild:esbuild": { "dependsOn": ["^build"] } - from
namedInputs(e.g.nx.jsonexclusion patterns for test files)production - Plugin configurations from
nx.json
Fix: Diff source and dest + . Add missing deps, merge relevant and .
package.jsonnx.jsontargetDefaultsnamedInputsnx import- 中的
package.json/dependenciesdevDependencies - 中的
nx.json(例如targetDefaults——对构建顺序至关重要)"@nx/esbuild:esbuild": { "dependsOn": ["^build"] } - 中的
nx.json(例如用于排除测试文件的namedInputs模式)production - 中的插件配置
nx.json
修复方法:对比源和目标的 + 。添加缺失的依赖,合并相关的和。
package.jsonnx.jsontargetDefaultsnamedInputsTypeScript Project References
TypeScript项目引用
After import, run . If it reports nothing but typecheck still fails, first, then again.
nx sync --yesnx resetnx sync --yes导入完成后,执行。如果命令无输出但类型检查仍失败,请先执行,再重新运行。
nx sync --yesnx resetnx sync --yesExplicit Executor Path Fixups
显式执行器路径修正
Inferred targets (via Nx plugins) resolve config relative to project root — no changes needed. Explicit executor targets (e.g. ) have workspace-root-relative paths (, , , , ) that must be prefixed with the import destination directory.
@nx/esbuild:esbuildmainoutputPathtsConfigassetssourceRoot通过Nx插件推断的目标会相对于项目根目录解析配置——无需修改。显式执行器目标(例如)的路径(、、、、)是相对于工作区根目录的,需要为其添加导入目标目录的前缀。
@nx/esbuild:esbuildmainoutputPathtsConfigassetssourceRootPlugin Detection
插件检测
- Whole-repo import: detects and offers to install plugins. Accept them.
nx import - Subdirectory import: Plugins NOT auto-detected. Manually add with . Check
npx nx add @nx/PLUGIN/includepatterns — defaults won't match alternate directories (e.g.exclude).apps-beta/ - Run after any plugin config changes.
npx nx reset
- 整个仓库导入:会自动检测并提示安装插件。请确认安装。
nx import - 子目录导入:不会自动检测插件。请手动通过添加。检查
npx nx add @nx/PLUGIN/include模式——默认配置可能不匹配自定义目录(例如exclude)。apps-beta/ - 任何插件配置变更后,请执行。
npx nx reset
Redundant Root Files (Whole-Repo Only)
冗余根目录文件(仅整个仓库导入)
Whole-repo import brings ALL source root files into the dest subdirectory. Clean up:
- — stale; dest has its own lockfile
pnpm-lock.yaml - — source workspace config; conflicts with dest
pnpm-workspace.yaml - — stale symlinks pointing to source filesystem
node_modules/ - — redundant with dest root
.gitignore.gitignore - — source Nx config; dest has its own
nx.json - — optional; keep or remove
README.md
Don't blindly delete — imported projects may extend it via relative paths.
tsconfig.base.json整个仓库导入会将源仓库的所有根目录文件带入目标子目录。请清理以下文件:
- ——已过期;目标仓库已有自己的锁文件
pnpm-lock.yaml - ——源仓库的工作区配置;与目标仓库冲突
pnpm-workspace.yaml - ——已过期的软链接,指向源文件系统
node_modules/ - ——与目标仓库根目录的
.gitignore重复.gitignore - ——源仓库的Nx配置;目标仓库已有自己的配置
nx.json - ——可选;可保留或删除
README.md
请勿盲目删除——导入的项目可能通过相对路径继承该配置。
tsconfig.base.jsonRoot ESLint Config Missing (Subdirectory Import)
根目录ESLint配置缺失(子目录导入)
Subdirectory import doesn't bring the source's root , but project configs reference .
eslint.config.mjs../../eslint.config.mjsFix order:
- Install ESLint deps first: (plus framework-specific plugins)
pnpm add -wD eslint@^9 @nx/eslint-plugin typescript-eslint - Create root (copy from source or create with
eslint.config.mjsbase rules)@nx/eslint-plugin - Then to register the plugin in
npx nx add @nx/eslintnx.json
Install explicitly — pnpm's strict hoisting won't auto-resolve this transitive dep of .
typescript-eslint@nx/eslint-plugin子目录导入不会带入源仓库的根目录,但项目配置会引用。
eslint.config.mjs../../eslint.config.mjs修复步骤:
- 先安装ESLint依赖:(按需添加框架特定插件)
pnpm add -wD eslint@^9 @nx/eslint-plugin typescript-eslint - 在根目录创建(从源仓库复制或使用
eslint.config.mjs的基础规则创建)@nx/eslint-plugin - 执行在
npx nx add @nx/eslint中注册插件nx.json
请显式安装——pnpm的严格提升规则不会自动解析的这个传递依赖。
typescript-eslint@nx/eslint-pluginESLint Version Pinning (Critical)
ESLint版本锁定(关键)
Pin ESLint to v9 (). ESLint 10 breaks and many plugins with cryptic errors like .
eslint@^9.0.0@nx/eslintCannot read properties of undefined (reading 'version')@nx/eslintCannot read properties of undefined (reading 'allow')pnpm.overridesjson
{ "pnpm": { "overrides": { "eslint": "^9.0.0" } } }请将ESLint锁定为v9版本()。ESLint 10会导致及许多插件崩溃,出现类似的模糊错误。
eslint@^9.0.0@nx/eslintCannot read properties of undefined (reading 'version')@nx/eslintCannot read properties of undefined (reading 'allow')pnpm.overridesjson
{ "pnpm": { "overrides": { "eslint": "^9.0.0" } } }Dependency Version Conflicts
依赖版本冲突
After import, compare key deps (, , framework-specific). If dest uses newer versions, upgrade imported packages to match (usually safe). If source is newer, may need to upgrade dest first. Use to enforce single-version policy if desired.
typescripteslintpnpm.overrides导入完成后,对比关键依赖版本(、、框架特定依赖)。如果目标仓库使用较新版本,可升级导入的包以匹配(通常是安全的)。如果源仓库版本更新,可能需要先升级目标仓库。若需要,可使用强制统一版本。
typescripteslintpnpm.overridesModule Boundaries
模块边界
Imported projects may lack . Add tags or update rules.
tags@nx/enforce-module-boundaries导入的项目可能缺少。请添加标签或更新规则。
tags@nx/enforce-module-boundariesProject Name Collisions (Multi-Import)
项目名称冲突(多仓库导入)
Same in across source and dest causes . Fix: Rename conflicting names (e.g. → ), update all dep references and import statements, . The root of each imported repo also becomes a project — rename those too.
namepackage.jsonMultipleProjectsWithSameNameError@org/api@org/teama-apipnpm installpackage.json源仓库与目标仓库的中存在相同的会导致。修复方法:重命名冲突的名称(例如 → ),更新所有依赖引用和导入语句,执行。每个导入仓库的根目录也会成为一个项目——请一并重命名。
package.jsonnameMultipleProjectsWithSameNameError@org/api@org/teama-apipnpm installpackage.jsonWorkspace Dep Import Ordering
工作区依赖导入顺序
pnpm installnx import"workspace:*"pnpm install --no-frozen-lockfile如果依赖尚未导入,过程中执行会失败,但文件操作仍会成功。修复方法:先导入所有项目,再执行。
"workspace:*"nx importpnpm installpnpm install --no-frozen-lockfile.gitkeep
Blocking Subdirectory Import
.gitkeep.gitkeep
阻止子目录导入
.gitkeepThe TS preset creates . Remove it and commit before importing.
packages/.gitkeepTS预设会创建。请删除该文件并提交后再进行导入。
packages/.gitkeepFrontend tsconfig Base Settings (Critical)
前端tsconfig基础设置(关键)
The TS preset defaults (, , ) are incompatible with frontend frameworks (React, Next.js, Vue, Vite). After importing frontend projects, verify the dest root :
module: "nodenext"moduleResolution: "nodenext"lib: ["es2022"]tsconfig.base.json- : Must be
moduleResolution(not"bundler")"nodenext" - : Must be
module(not"esnext")"nodenext" - : Must include
liband"dom"(frontend projects need these)"dom.iterable" - :
jsxfor React-only workspaces, per-project for mixed frameworks"react-jsx"
For subdirectory imports, the dest root tsconfig is authoritative — update it. For whole-repo imports, imported projects may extend their own nested , making this less critical.
tsconfig.base.jsonIf the dest also has backend projects needing , use per-project overrides instead of changing the root.
nodenextGotcha: TypeScript does NOT merge arrays — a project-level override replaces the base array entirely. Always include all needed entries (e.g. , , ) in any project-level .
libes2022domdom.iterablelibTS预设的默认配置(、、)与前端框架(React、Next.js、Vue、Vite)不兼容。导入前端项目后,请验证目标仓库根目录的:
module: "nodenext"moduleResolution: "nodenext"lib: ["es2022"]tsconfig.base.json- :必须设置为
moduleResolution(不能是"bundler")"nodenext" - :必须设置为
module(不能是"esnext")"nodenext" - :必须包含
lib和"dom"(前端项目需要这些)"dom.iterable" - :纯React工作区设置为
jsx,混合框架工作区可按项目单独配置"react-jsx"
对于子目录导入,目标仓库根目录的tsconfig是权威配置——请更新它。对于整个仓库导入,导入的项目可能继承自己嵌套的,因此这一点不太关键。
tsconfig.base.json如果目标仓库同时有需要配置的后端项目,请使用项目级别的覆盖配置,而非修改根目录配置。
nodenext注意:TypeScript不会合并数组——项目级别的覆盖配置会完全替换基础数组。请确保项目级数组包含所有必要的条目(例如、、)。
liblibes2022domdom.iterable@nx/react
Typings for Libraries
@nx/react@nx/react
库类型定义
@nx/reactReact libraries generated with reference and in their tsconfig . These fail with unless is installed in the dest workspace.
@nx/react:library@nx/react/typings/cssmodule.d.ts@nx/react/typings/image.d.tstypesCannot find type definition file@nx/reactFix:
pnpm add -wD @nx/react使用生成的React库会在其tsconfig的中引用和。如果目标仓库未安装,会出现错误。
@nx/react:librarytypes@nx/react/typings/cssmodule.d.ts@nx/react/typings/image.d.ts@nx/reactCannot find type definition file修复方法:执行
pnpm add -wD @nx/reactJest Preset Missing (Subdirectory Import)
Jest预设缺失(子目录导入)
Nx presets create at the workspace root, and project jest configs reference it (e.g. ). Subdirectory import does NOT bring this file.
jest.preset.js../../jest.preset.jsFix:
- Run — registers
npx nx add @nx/jestin@nx/jest/pluginand updatesnx.jsonnamedInputs - Create at workspace root (see
jest.preset.jsfor content) —references/JEST.mdonly creates this when a generator runs, not on barenx addnx add - Install test runner deps:
pnpm add -wD jest jest-environment-jsdom ts-jest @types/jest - Install framework-specific test deps as needed (see )
references/JEST.md
For deeper Jest issues (tsconfig.spec.json, Babel transforms, CI atomization, Jest vs Vitest coexistence), see .
references/JEST.mdNx预设会在工作区根目录创建,项目的jest配置会引用它(例如)。子目录导入不会带入该文件。
jest.preset.js../../jest.preset.js修复步骤:
- 执行——在
npx nx add @nx/jest中注册nx.json并更新@nx/jest/pluginnamedInputs - 在工作区根目录创建(可参考
jest.preset.js中的内容)——references/JEST.md仅在生成器运行时创建该文件,裸nx add不会创建nx add - 安装测试运行器依赖:
pnpm add -wD jest jest-environment-jsdom ts-jest @types/jest - 按需安装框架特定测试依赖(参考)
references/JEST.md
若遇到更复杂的Jest问题(tsconfig.spec.json、Babel转换、CI原子化、Jest与Vite共存),请查看。
references/JEST.mdTarget Name Prefixing (Whole-Repo Import)
目标名称前缀(整个仓库导入)
When importing a project with existing npm scripts (, , , ), Nx plugins auto-prefix inferred target names to avoid conflicts: e.g. , , .
builddevstartlintnext:buildvite:buildeslint:lintFix: Remove the Nx-rewritten npm scripts from the imported , then either:
package.json- Accept the prefixed names (e.g. )
nx run app:next:build - Rename plugin target names in to use unprefixed names
nx.json
当导入的项目已有npm脚本(、、、)时,Nx插件会自动为推断的目标名称添加前缀以避免冲突:例如、、。
builddevstartlintnext:buildvite:buildeslint:lint修复方法:从导入的中删除Nx重写的npm脚本,然后选择以下方式之一:
package.json- 接受带前缀的名称(例如)
nx run app:next:build - 在中重命名插件目标名称,使用无前缀的名称
nx.json
Non-Nx Source Issues
非Nx源仓库问题
When the source is a plain pnpm/npm workspace without .
nx.json当源仓库是没有的普通pnpm/npm工作区时。
nx.jsonnpm Script Rewriting (Critical)
npm脚本重写(关键)
Nx rewrites scripts during init, creating broken commands (e.g. → ). Fix: Remove all rewritten scripts — Nx plugins infer targets from config files.
package.jsonvitest runnx test runNx在初始化过程中会重写中的脚本,生成无效命令(例如 → )。修复方法:删除所有被重写的脚本——Nx插件会从配置文件中推断目标。
package.jsonvitest runnx test runnoEmit
→ composite
+ emitDeclarationOnly
(Critical)
noEmitcompositeemitDeclarationOnlynoEmit
→ composite
+ emitDeclarationOnly
(关键)
noEmitcompositeemitDeclarationOnlyPlain TS projects use , incompatible with Nx project references.
"noEmit": trueSymptoms: "typecheck target is disabled because one or more project references set 'noEmit: true'" or TS6310.
Fix in all imported tsconfigs:
- Remove . If inherited via extends chain, set
"noEmit": trueexplicitly."noEmit": false - Add ,
"composite": true,"emitDeclarationOnly": true"declarationMap": true - Add and
"outDir": "dist""tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" - Add if missing. Remove settings now inherited from base.
"extends": "../../tsconfig.base.json"
普通TS项目使用,与Nx项目引用不兼容。
"noEmit": true症状:"typecheck目标已禁用,因为一个或多个项目引用设置了'noEmit: true'" 或 TS6310错误。
修复方法(所有导入的tsconfig文件):
- 删除。如果是通过继承链获得的该配置,请显式设置
"noEmit": true。"noEmit": false - 添加、
"composite": true、"emitDeclarationOnly": true"declarationMap": true - 添加和
"outDir": "dist""tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" - 若缺失,请添加。删除现在从基础配置继承的设置。
"extends": "../../tsconfig.base.json"
Stale node_modules and Lockfiles
过期的node_modules与锁文件
nx importnode_modules/pnpm-lock.yamlFix: , then .
rm -rf imported/node_modules imported/pnpm-lock.yaml imported/pnpm-workspace.yaml imported/.gitignorepnpm installnx importnode_modules/pnpm-lock.yaml修复方法:执行,然后执行。
rm -rf imported/node_modules imported/pnpm-lock.yaml imported/pnpm-workspace.yaml imported/.gitignorepnpm installESLint Config Handling
ESLint配置处理
- Legacy (ESLint 8): Delete all
.eslintrc.json, remove v8 deps, create flat.eslintrc.*.eslint.config.mjs - Flat config (): Self-contained configs can often be left as-is.
eslint.config.js - No ESLint: Create both root and project-level configs from scratch.
- 传统(ESLint 8):删除所有
.eslintrc.json文件,移除v8版本依赖,创建扁平配置.eslintrc.*。eslint.config.mjs - 扁平配置():独立的配置通常可直接保留。
eslint.config.js - 无ESLint配置:从头创建根目录和项目级别的配置。
TypeScript paths
Aliases
pathsTypeScript paths
别名
pathsNx uses + pnpm workspace linking instead of tsconfig . If packages have proper , paths are redundant. Otherwise, update paths for the new directory structure.
package.json"exports""paths""exports"Nx使用的 + pnpm工作区链接,而非tsconfig的。如果包有正确的配置,是冗余的。否则,请根据新的目录结构更新。
package.json"exports""paths""exports"pathspathsTechnology-specific Guidance
技术特定指南
Identify technologies in the source repo, then read and apply the matching reference file(s).
Available references:
references/GRADLE.md- — Jest testing:
references/JEST.mdsetup, jest.preset.js, testing deps by framework, tsconfig.spec.json, Jest vs Vitest coexistence, Babel transforms, CI atomization.@nx/jest/plugin - — Next.js projects:
references/NEXT.mdtargets,@nx/next/plugin, Next.js TS config (withNx,noEmit), auto-installing deps via wrong PM, non-Nxjsx: "preserve"imports, mixed Next.js+Vite coexistence.create-next-app references/TURBOREPO.md- — Vite projects (React, Vue, or both):
references/VITE.mdtypecheck target,@nx/vite/plugin/resolve.aliasfixes, framework deps, Vue-specific setup, mixed React+Vue coexistence.__dirname
识别源仓库中的技术栈,然后阅读并应用对应的参考文档。
可用参考文档:
references/GRADLE.md- — Jest测试:
references/JEST.md配置、jest.preset.js、各框架测试依赖、tsconfig.spec.json、Jest与Vitest共存、Babel转换、CI原子化。@nx/jest/plugin - — Next.js项目:
references/NEXT.md目标、@nx/next/plugin、Next.js TS配置(withNx、noEmit)、错误包管理器自动安装依赖、非Nxjsx: "preserve"导入、Next.js+Vite混合共存。create-next-app references/TURBOREPO.md- — Vite项目(React、Vue或两者混合):
references/VITE.md类型检查目标、@nx/vite/plugin/resolve.alias修复、框架依赖、Vue特定配置、React+Vue混合共存。__dirname