使用TypeScript 2命名空间,如何获得代码来识别添加到子文件夹中的命名空间中的类。
(我使用的是AngularJS 1.5和Webpack,但两者都不应该参与其中。)
在下面的示例中,指令D1位于指令下的文件夹中,而_bootstrap_directives.ts无法解析它。它会得到以下错误:
error TS2339:在“类型指令”.类型中不存在属性“D1Directive”
也许我只需要创建myLibrary.d.ts来显式地定义契约?
-
directives
> d1
> d1.directive.ts
> d1.scss
> _bootstrap_directives.ts
> d2.directive.ts-
> d1.directive.ts (d2.directive is the same with a different class name and no scss import)
import './d1.scss'; // for webpack
namespace MyLibrary.Directives {
export class D1Directive implements ng.IDirective {
restrict: string = 'A';
scope: boolean = false;
constructor() {
// noop
}
static factory(): ng.IDirectiveFactory {
const directive = () => {
return new D1Directive();
}
return directive;
}
}
}-
> _bootstrap_directives.ts (
// Property 'D1Directive' does not exist on type 'typeof Directives'.
import './d1/d1.directive'; // for webpack
angular.module('myLibrary')
.directive('d1', MyLibrary.Directives.D1Directive.factory());
// This one works
import './d2.directive'; // for webpack
angular.module('myLibrary')
.directive('d2', MyLibrary.Directives.D2Directive.factory());我正在使用2015。
发布于 2016-10-26 17:47:25
原来webpack才是问题所在。把这个留在这里帮助社区。
将这一行从d1.directive.ts移到引导文件删除了问题。
import './d1.scss';因此,吸取的教训--不要导入名称空间之外的子文件夹。
发布于 2017-03-26 00:01:40
我和这个问题斗争了好几天,尽管我现在似乎已经掌握了它,但它仍然让我发疯。
对于我的项目中的本地/内部开发,我不再使用模块(或名称空间),这应该使它始终在全局范围上运行(虽然不是最好的,但我认为它目前是有效的)。
你进口的东西坏了是因为..。
在TypeScript中,就像在ECMAScript 2015中一样,任何包含顶级导入或导出的文件都被视为模块。
那么为什么作为一个模块会让你所有的参考资料消失?
模块在自己的范围内执行,而不是在全局范围内执行;这意味着在模块中声明的变量、函数、类等在模块之外不可见,除非它们是使用导出表单之一显式导出的。相反,要使用从不同模块导出的变量、函数、类、接口等,必须使用导入表单之一导入变量、函数、类和接口。
https://stackoverflow.com/questions/40267190
复制相似问题