我使用 NPM 工作区和 Typescript 设置了 NodeJS monorepo。它在没有 Typescript 的情况下工作得很好,但是引入 TS 会带来一些依赖解决错误。当前目录设置:
+-- node_modules
+-- package.json
+-- tsconfig.json
+-- tsconfig.build.json
+-- packages
+-- core
| +-- package.json
| +-- tsconfig.json
| +-- src
| +-- index.ts
+-- shared
| +-- package.json
| +-- tsconfig.json
| +-- src
| +-- helper.ts
Running npm ls
确认所有内容都已正确符号链接:
[email protected] /cdn-cgi/l/email-protection C:\Users\<user>\Documents\Temp\monorepoDemo
├─┬ @my-packages/[email protected] /cdn-cgi/l/email-protection -> .\packages\core
│ └── @my-packages/[email protected] /cdn-cgi/l/email-protection deduped -> .\packages\shared
└── @my-packages/[email protected] /cdn-cgi/l/email-protection -> .\packages\shared
我有一个正在导出的虚拟辅助函数helper.ts
in shared
。正在导入哪个index.ts
in core
。根package.json
, tsconfig.ts
and tsconfig.build.json
:
{
"name": "monorepoDemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node packages/core/src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc -b --verbose tsconfig.build.json"
},
"author": "",
"license": "ISC",
"workspaces": [
"packages\\core",
"packages\\shared"
]
}
{
"compilerOptions": {
"composite": true,
"target": "es2021",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
{
"files": [],
"references": [
{
"path": "packages/core"
},
{
"path": "packages/shared"
}
]
}
The package.json
and tsconfig.json
of core
:
{
"name": "@my-packages/core",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@my-packages/shared": "^1.0.0"
}
}
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"baseUrl": ".",
"paths": {
"@my-packages/shared": ["../shared"]
}
},
"references": [{ "path": "../shared" }],
"exclude": ["dist"]
}
The package.json
and tsconfig.json
of shared
:
{
"name": "@my-packages/shared",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"
},
"exclude": ["dist"]
}
以及源代码index.ts
and helper.ts
:
import { helper } from "@my-packages/shared"
(async () => {
console.log("Bootstrapping from core package")
helper()
})()
export function helper(): void {
console.log("Running from shared package")
}
我遇到的错误index.ts
:
Cannot find module '@my-packages/shared' or its corresponding type declarations.ts(2307)
我认为这与缺少声明文件有关,因此尝试创建一个helper.ts
但没有到达任何地方