ten*_*obi 10 typescript angular
我想创建本地模块在我的打字稿(与角2到任何文件)的应用程序,然后简单的参考与进口模块一样myApp/components,myApp/pipes等等,不使用相对路径(../../../MyComponent),因为我有现在做.
例如,Angular 2可以像这样使用.(我还没有找到他们是如何做到的)
import {Component} from 'angular2/core';
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这种行为?
我做了一些文件,如components.ts,templates.ts等在那里我从当前部分导出文件:
export * from './menu/item';
export * from './menu/logo';
export * from './article/article';
export * from './article/sidebar';
Run Code Online (Sandbox Code Playgroud)
...然后我有一个主文件myApp.ts,我声明模块如下:
declare module 'myapp/components' {
export * from './application/components';
}
declare module 'myapp/templates' {
export * from './application/templates';
}
Run Code Online (Sandbox Code Playgroud)
但是这个文件没有生成任何东西,因此TS构建告诉我错误 ...file_path...(4,9): error TS2305: Module ''myapp/components'' has no exported member 'AlfaBeta'.
顺便说一句.我tsconfig.json看起来像这样:
{
"compilerOptions": {
"target": "ES5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
Run Code Online (Sandbox Code Playgroud)
在打字稿2.0+有一个baseUrl和paths财产tsconfig.json,您可以使用.
在你的情况下,你会想要:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"myapp/components": [
"menu/item",
"menu/logo",
"article/article",
"article/sidebar",
],
"myapp/templates": [
"templates/*" // whatever files you want to include
]
}
// etc...
},
// etc...
}
Run Code Online (Sandbox Code Playgroud)
在baseUrl您可以指定基目录(通常是项目的根目录).这允许您从目录结构中的任何位置进行导入,就像从中指定的目录进行导入一样baseUrl.
例如,使用目录结构...
folder1
- folder2
- file2.ts
file1.ts
Run Code Online (Sandbox Code Playgroud)
...指定a "baseUrl": "."将允许您通过执行以下操作导入file1.ts,file2.ts就像您在根目录中一样:
import * as File1 from "file1";
Run Code Online (Sandbox Code Playgroud)
最重要的是baseUrl你可以添加paths.这对你很有用,必须和它一起使用baseUrl.在paths您可以指定模式匹配和文件的列表中该模式包含.这在github问题中有说明,如下所示:
"paths": {
"pattern-1": ["list of substitutions"],
"pattern-2": ["list of substitutions"],
...
"pattern-N": ["list of substitutions"]
}
Run Code Online (Sandbox Code Playgroud)
请注意,这只会使它编译.我相信你还必须配置SystemJS以便在运行时使用它,并且可能需要使用桶文件并设置指向桶文件的路径.
您可以在github问题中阅读有关此内容的更多信息,或阅读我的其他相关答案,其中还显示了一个前TS 2.0解决方案.