我在使用 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
从 '../../../../frameworks/il8n/language-service' 导入 { LanguageService };
另一种方法是使用桶,如下所示:
//login.ts
从 '../../../../frameworks/index' 导入 { LanguageService };
其中 frameworks/index.ts
正在执行 export * 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 都会提示(所有 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 构建配置,以便我可以进行“简单”导入?
最佳答案
所以,这个问题是基于 Angular2 Seed (Advanced) 存储库发现的 here 。我发布了issue那里也有(在那里你可以看到确切的修复)。长话短说:
您需要 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
文件夹中的一个文件,用于导出该目录中的模块。例如,如果您的框架目录中有一个 language.component.ts
文件,则在 frameworks/index.ts
文件中您将执行以下操作:
从“path/to/language.component”导出*;
。
这允许您在项目中import {LanguageComponent} from 'frameworks';
(只要您位于frameworks
目录之外)。
希望这有帮助!
关于typescript - SystemJS 和 ES 模块导入的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38618257/