我在两个单独的文件中有两个类,一个从另一个扩展。基类包含一些使用节点模块的 import
语句。我不清楚为什么派生类(在单独的文件中)不能识别基类!!!???
有人可以澄清一下吗?
// UtilBase.ts
/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/packages.d.ts" />
import * as path from "path"; // <---- THIS LINE BREAKS THE BUILD!!!!
namespace My.utils {
export class UtilBase {
protected fixPath(value: string): string {
return value.replace('/', path.sep);
}
}
}
然后
// UtilOne.ts
/// <reference path="UtilBase.ts" />
namespace My.utils {
export class UtilOne extends My.utils.UtilBase {
}
}
编译后得到:
src/UtilOne.ts(6,47): error TS2339: Property 'UtilBase' does not
exist on type 'typeof utils'
最佳答案
命名空间的解决方案(不推荐)
要解决您的问题,您可以导出您的命名空间:
// UtilBase.ts
import * as path from "path";
export namespace My.utils {
export class UtilBase {
protected fixPath(value: string): string {
return value.replace('/', path.sep);
}
}
}
然后,您应该能够导入它:
// UtilOne.ts
import {My} from './UtilBase';
namespace My.utils {
export class UtilOne extends My.utils.UtilBase {
}
}
但是,如果目的是整理代码,it is a bad practice to use namespaces and (ES6) modules at the same time .使用 Node.js,您的文件是模块,那么您应该避免命名空间。
使用没有命名空间的ES6 模块
TypeScript 很好地支持 ES6 模块的语法:
// UtilBase.ts
import * as path from "path";
export default class UtilBase {
protected fixPath(value: string): string {
return value.replace('/', path.sep);
}
}
// UtilOne.ts
import UtilBase from './UtilBase';
export default class UtilOne extends UtilBase {
}
这是推荐的方式。 ES6 模块通过重命名每个导入资源的能力防止命名冲突。
它将在 Node.js 上运行。
有关 ES6 模块语法的详细介绍,read this article .
使用文件tsconfig.json
而不是 /// <reference
注意:语法/// <reference
被 the file tsconfig.json
取代. Node.js 的示例:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
},
"exclude": [
"node_modules"
]
}
关于typescript - 如何在 TypeScript 中通过导入使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37565709/