網站搜尋

typescript - SystemJS 與 ES 模組匯入的相對路徑


我在使用 SystemJS 和 ES 匯入語法時,導入 Angular2 組件遇到問題。

專案結構:

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.ts 正在執行 export * from './il8n/language-service';

我不想每次需要導入某個東西時都寫 ../../../ 等等;如果我能直接寫 import { LanguageService } from 'frameworks'; 那就太好了

到目前為止,我已經能夠使用 SystemJS 的「map」選項來讓我的建構過程運作,如下所示:

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

然而,每當我做類似以下的操作時,我的 IDE 就會抱怨(所有 IntelliSense 功能完全壞掉):

`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 的構建配置,讓我可以進行“簡單”的導入嗎?

答案#1

所以,這個問題是基於這裡的 Angular2 Seed(進階)倉庫。我也在那裡發佈了一個問題(你可以看到確切的修復方法)。長話短說:

你需要 TypeScript 2.0 才能在 tsconfig 文件中使用 paths 和 baseUrl 選項。然後在你的 SystemJS 配置文件中,你需要在 paths 和 packages 選項中添加一些配置,如下所示:

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

index.ts 是位於你的 frameworks 資料夾內的一個檔案,用來匯出該目錄中的模組。例如,如果你在 frameworks 資料夾內的某個地方有一個 language.component.ts 檔案,在 frameworks/index.ts 檔案中你會這麼做:

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

這允許你在專案中使用 import {LanguageComponent} from 'frameworks';(只要你位於 frameworks 目錄之外)。

希望這對你有幫助!