2016-10-26 25 views
1

使用TypeScript 2名稱空間,我如何獲取代碼以識別添加到子文件夾中名稱空間的類。TypeScript 2.0:如何在同一個命名空間中引用對象,但在子文件夾中引用對象?

(我使用AngularJS 1.5和的WebPack,但既不這些發揮在此的一部分。)

在下面的例子中,指令D1是下指示一個文件夾中,並且可以_bootstrap_directives.ts沒有解決它。它得到這個錯誤:

錯誤TS2339:'typeof指令'類型中不存在屬性'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()); 

我使用Visual Studio 2015年

回答

0

原來的WebPack是問題。留下來幫助社區。

將此行從d1.directive.ts移至引導程序文件中,可以消除此問題。

import './d1.scss'; 

所以吸取了教訓 - 不要導入命名空間以外的子文件夾。

+0

一般的教訓是避免命名空間(內部模塊)。命名空間是一個概念,在明確表示JavaScript將轉移到具有ES6的適當模塊系統之前,已經引入了這個概念。現在,你應該[只使用模塊](https://www.typescriptlang.org/docs/handbook/modules.html)(即TypeScript中的「外部模塊」) – poke

+0

我實際上已經切換到使用模塊而不是命名空間。不幸的是,發生完全相同的問題。模塊Library.Blah.Blah上方的導入語句會導致TS編譯器找不到導出的類。即使該.ts文件位於同一個文件夾中。 –

+0

我不會說webpack是問題。我會說頂部的導入是問題(TypeScript)。我意識到這篇文章有點舊了,但是我一直在爲這個上週做鬥爭。查看我的答案瞭解更多信息。 –

2

我一直在爲這個問題爭取好幾天,儘管現在我似乎已經掌握了它,但它仍然讓我瘋狂。我停止使用模塊(或名稱空間),這應該使它始終運行在全局範圍內(不是最大的,但現在我猜)。

的進口量破事的原因..

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.

那麼,爲什麼作爲一個模塊,讓你的所有引用消失? ...

Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.

See here for more info

相關問題