我正在编写一个可能包含浏览器和节点的不同实现的库。
这就是我的目录结构的样子
root
├── myclass
│ ├── myclass.d.ts
│ │
│ ├── browser
│ │ └── myclass.ts
│ │
│ └── node
│ └── myclass.ts
│
├── index.ts (references myclass.d.ts)
│
├── tsconfig.browser.json
└── tsconfig.node.json
index.ts
import myclass from "./myclass/myclass"
myclass.print();
MyClass的\ myclass.d.ts
declare class myclass {
public static print();
}
export default myclass;
MyClass的\节点\ myclass.ts
import myclass from "../myclass";
export default class myclass_browser implements myclass {
public static print() {
console.log("node");
}
}
我希望有两个单独的tsconfigs(tsconfig.browser.json和tsconfig.node.json),这样每个配置都会使编译器输出包含特定于平台的实现的js文件。
如何根据配置文件使打字稿编译器拾取正确的实现,并且这样做适用于项目中具有此类格式的所有类。
更新:好的,所以我尝试在我的tsconfig中使用paths
,这就是我tsconfig.node.json
的样子
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"rootDir": "./",
"outDir": "../out/node",
"baseUrl": "./",
"paths": {
"myclass/*": ["./myclass/node/*"]
}
}
}
但是模块分辨率不起作用,因为编译器停在myclass.d.ts
这是分辨率跟踪的样子
======== Resolving module './myclass/myclass' from 'D:/tsabs/root/index.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
Loading module as file / folder, candidate module location 'D:/tsabs/root/myclass/myclass', target file type 'TypeScript'.
File 'D:/tsabs/root/myclass/myclass.ts' does not exist.
File 'D:/tsabs/root/myclass/myclass.tsx' does not exist.
File 'D:/tsabs/root/myclass/myclass.d.ts' exist - use it as a name resolution result.
======== Module name './myclass/myclass' was successfully resolved to 'D:/tsabs/root/myclass/myclass.d.ts'. ========
======== Resolving module '../myclass' from 'D:/tsabs/root/myclass/browser/myclass.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
Loading module as file / folder, candidate module location 'D:/tsabs/root/myclass/myclass', target file type 'TypeScript'.
File 'D:/tsabs/root/myclass/myclass.ts' does not exist.
File 'D:/tsabs/root/myclass/myclass.tsx' does not exist.
File 'D:/tsabs/root/myclass/myclass.d.ts' exist - use it as a name resolution result.
======== Module name '../myclass' was successfully resolved to 'D:/tsabs/root/myclass/myclass.d.ts'. ========
======== Resolving module '../myclass' from 'D:/tsabs/root/myclass/node/myclass.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
Loading module as file / folder, candidate module location 'D:/tsabs/root/myclass/myclass', target file type 'TypeScript'.
File 'D:/tsabs/root/myclass/myclass.ts' does not exist.
File 'D:/tsabs/root/myclass/myclass.tsx' does not exist.
File 'D:/tsabs/root/myclass/myclass.d.ts' exist - use it as a name resolution result.
======== Module name '../myclass' was successfully resolved to 'D:/tsabs/root/myclass/myclass.d.ts'. ========