2016-07-27 152 views
2

使用SystemJS和ES導入語法時,導入Angular2組件時遇到問題。SystemJS和ES模塊導入的相對路徑

項目結構:

ROOT 
|_src 
    |_client 
    |_app 
     |_frameworks 
     |_il8n 
     |_analytics 
     |_main 
     |_components 
     |_pages 
     |_utility 

比方說,我有一個文件:ROOT/src/client/app/frameworks/il8n/language-service.ts和另一個文件:ROOT/src/client/app/main/pages/login/login.ts。在login.ts我想導入language.ts,這樣做的一個方法是,像這樣:

//login.ts import { LanguageService } from '../../../../frameworks/il8n/language-service';

另一種方式來做到這一點,利用桶,就像這樣:

//login.ts import { LanguageService } from '../../../../frameworks/index';

其中frameworks/index.tsexport * from './il8n/language-service';

我不想做../../../等我每次需要進口一些時間;這將是很好,如果我可以做import { LanguageService } from 'frameworks';

到目前爲止,我已經能夠讓我的構建過程中使用SystemJS的"map" option像這樣的工作:

map: { 
     frameworks: 'src/client/app/frameworks/index', 
     components: 'src/client/app/main/components/index', 
     pages: 'src/client/app/main/pages/index' 
    } 

然而,我的IDE抱怨(所有的智能感知功能完全打破),只要我做這樣的事情:

`import { LanguageService } from 'frameworks';` 

這裏是我的tsconfig.json文件:

{ 
    "compilerOptions": { 
     "target": "es5", 
     "module": "commonjs", 
     "declaration": false, 
     "removeComments": true, 
     "noLib": false, 
     "emitDecoratorMetadata": true, 
     "experimentalDecorators": true, 
     "sourceMap": true, 
     "pretty": true, 
     "allowUnreachableCode": false, 
     "allowUnusedLabels": false, 
     "noImplicitAny": true, 
     "noImplicitReturns": true, 
     "noImplicitUseStrict": false, 
     "noFallthroughCasesInSwitch": true, 
     "baseUrl": "./src", 
     "paths": { 
      "frameworks": ["client/app/frameworks"], 
      "components": ["client/app/main/components"], 
      "pages": ["client/app/main/pages"], 
      "utility": ["client/app/main/utility"] 
     } 
    }, 
    "compileOnSave": false 
} 

是否有一種方法可以同時滿足我的IDE和SystemJS構建配置,以便我可以執行「簡單」導入?

+0

你使用哪個IDE版本? – anstarovoyt

+0

我使用WebStorm 2016.2 – exk0730

+0

可以請你分享你的項目嗎?該功能必須適用於WS2016。2 – anstarovoyt

回答

3

所以,這個問題是基於Angular2種子(高級)回購發現here。我在那裏也發佈了一個issue(在這裏你可以看到確切的修復)。長話短說:

您需要TypeScript 2.0才能在您的tsconfig文件中使用pathsbaseUrl選項。然後在你的SystemJS配置文件,你需要一些配置添加到pathspackages選項如下:

packages: { 
    ... 
    frameworks: { defaultExtension: js, main: index.js } 
    ... 
}, 
paths: { 
    ... 
    frameworks: 'relative/path/to/frameworks/folder' 
    ... 
} 

index.ts裏面其中出口模塊在該目錄中的文件夾frameworks文件。例如,如果您的框架目錄中有language.component.ts文件,則可以使用frameworks/index.ts文件:

export * from 'path/to/language.component';

這允許您在項目中執行import {LanguageComponent} from 'frameworks';(只要您在frameworks目錄之外)。

希望這會有所幫助!