Jol*_*lle 10 node.js npm typescript yarnpkg yarn-workspaces
我有一个相当大的项目 A 使用 Node 和 Typescript。在项目 AI 中有很多不同的模块,我想在另一个项目 B 中重用它们。
因此我用这个 tsconfig.json 构建了项目 A:
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"sourceMap": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"typeRoots": ["./node_modules/@types", "./modules/@types"]
},
"exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)
因此所有文件都以这种方式构建到 /dist 文件夹中:
要在另一个项目中使用这些 moduleA 和 moduleB,我将以下内容添加到项目 A 中的 package.json 中:
"name": "projectA",
"version": "1.0.0",
"description": "...",
"main": "dist/moduleA.js",
"typings": "dist/moduleA.d.ts",
Run Code Online (Sandbox Code Playgroud)
我使用纱线工作区来访问项目 A 作为项目 B 中的包。但问题是,在import {ModuleA} from 'projectA'我的新项目 B 中使用时,我只能访问模块 A?那么如何从 ProjectA 访问更多模块呢?
简单地将所有出口合并为一个index.ts对您有用吗?
package.json(项目A):
{
"main": "dist/index.js",
"typings": "dist/index.d.ts",
...
}
Run Code Online (Sandbox Code Playgroud)
索引.ts(项目A):
// Adjust the relative import paths
// and identifiers to your structure
export { ModuleA } from "./moduleA";
export { ModuleB } from "./moduleB";
Run Code Online (Sandbox Code Playgroud)
项目B中的一些模块:
import {ModuleA, ModuleB} from 'projectA'
Run Code Online (Sandbox Code Playgroud)
我相信您正在寻找的是: https://nodejs.org/api/packages.html#packages_package_entry_points
不清楚 TypeScript 目前是否支持: https ://github.com/microsoft/TypeScript/issues/33079
看来你可以通过在 package.json 中使用类似的内容来解决这个问题:
{
...
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"dist/index.d.ts": [ "dist/index.d.ts" ],
"*": [ "dist/*" ]
}
},
"exports": {
".": "./dist/index.js",
"./": "./dist/"
},
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19741 次 |
| 最近记录: |