【发布时间】:2022-01-26 10:02:51
【问题描述】:
我已经这样设置了我的项目(使用yarn workspaces):
package.json
tsconfig.json
packages/shared
index.ts
other.ts
package.json
tsconfig.json
web
index.ts
package.json
tsconfig.json
这些是文件内容:
根package.json:
{
"name": "monorepo",
"private": true,
"workspaces": [
"web",
"packages/shared"
],
"dependencies": {
"typescript": "^4.5.4"
}}
根tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": [
"**/node_modules",
"**/.*/",
"**/jest.config.js",
"**/dist"
],
"references": [
{
"path": "web/tsconfig.json"
},
{
"path": "packages/shared/tsconfig.json"
}
]
}
打包/共享package.json:
{
"name": "shared",
"private": true,
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc"
}
}
打包/共享index.ts:
export const test = (a: number, b: number) => {
return a + b;
};
打包/共享other.ts:
export const add = (a: number, b: number): number => a + b;
打包/共享tsconfig.json:
{
"compilerOptions": {
"composite": true,
"target": "es5",
"module": "commonjs",
"rootDir": ".",
"declaration": true,
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
网络package.json:
{
"name": "web",
"private": true,
"main": "dist/index.js",
"types": "dist/index.d.ts",
"version": "1.0.0",
"dependencies": {
"shared": "1.0.0"
},
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}
网络index.ts:
import { test } from "shared";
import { add } from "shared/other";
console.log(add(1, 2));
console.log(test(1, 2));
网络tsconfig.json:
{
"compilerOptions": {
"composite": true,
"target": "es5",
"module": "commonjs",
"rootDir": ".",
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"references": [
{
"path": "../packages/shared/tsconfig.json"
}
]
}
两个包都编译成功,但是当我运行web/dist/index.js 时,我得到Error: Cannot find module 'shared/other'。经过进一步检查,我发现在编译的 JS 代码中只有 shared/index.js 正确链接(到 dist/ 文件夹,见下图)。我怀疑这与package.json 中的main 或types 属性有关?
(index.js 正在正常解析中)
(这应该是shared/dist/other 而不是shared/other)
如何使所有shared 包文件对web 都“可见”?
【问题讨论】:
-
最简单的解决方案是在
shared:nodejs.org/api/packages.html#subpath-exports 中使用exports映射子路径导出。但是我认为 typescript 还不支持。 -
exports: {"./shared/other": "./shared/dist/other.js" }
标签: javascript node.js typescript package.json