Typescript 类型脚本声明模块
我想在我的TypeScript(使用Angular 2)应用程序中创建本地模块,然后使用导入模块(如Typescript 类型脚本声明模块,typescript,angular,Typescript,Angular,我想在我的TypeScript(使用Angular 2)应用程序中创建本地模块,然后使用导入模块(如myApp/components,myApp/pipes等)简单引用任何文件,而不是像我现在必须做的那样使用相对路径(../../../MyComponent) 例如,Angular 2可以这样使用。(我还没发现他们是怎么做到的) 我如何实现这种行为 我做了一些文件,如components.ts,templates.ts等,其中我从当前部分导出了文件: export * from './menu
myApp/components
,myApp/pipes
等)简单引用任何文件,而不是像我现在必须做的那样使用相对路径(../../../MyComponent)
例如,Angular 2可以这样使用。(我还没发现他们是怎么做到的)
我如何实现这种行为
我做了一些文件,如
components.ts
,templates.ts
等,其中我从当前部分导出了文件:
export * from './menu/item';
export * from './menu/logo';
export * from './article/article';
export * from './article/sidebar';
。。。然后我有一个主文件myApp.ts
,我在其中声明如下模块:
declare module 'myapp/components' {
export * from './application/components';
}
declare module 'myapp/templates' {
export * from './application/templates';
}
但此文件不会生成任何内容,因此TS build会告诉我一些错误,如…file\u path…(4,9):错误TS2305:模块“myapp/components”没有导出的成员“AlfaBeta”。
顺便说一句,我的tsconfig.json
如下所示:
{
"compilerOptions": {
"target": "ES5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
在TypeScript 2.0+中,您可以使用
tsconfig.json
中的baseUrl
和path
属性
在您的情况下,您需要:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"myapp/components": [
"menu/item",
"menu/logo",
"article/article",
"article/sidebar",
],
"myapp/templates": [
"templates/*" // whatever files you want to include
]
}
// etc...
},
// etc...
}
在baseUrl
中,可以指定基本目录(通常是项目的根目录)。这允许您从目录结构中的任何位置进行导入,就像从baseUrl
中指定的目录进行导入一样
例如,使用目录结构
folder1
- folder2
- file2.ts
file1.ts
…指定“baseUrl”:“
将允许您在file2.ts
中导入file1.ts
,就像您在根目录中一样,方法是:
import * as File1 from "file1";
在baseUrl
之上,您可以添加路径
。这对您很有用,必须与baseUrl
一起使用。在路径中,您可以指定要匹配的模式以及要包含在该模式中的文件列表。如图所示:
注意,这只会使它编译。我相信您还必须配置SystemJS才能在运行时运行,这可能需要使用文件并设置指向桶文件的路径
您可以在或阅读我的其他相关答案中了解更多信息,其中也显示了TS 2.0之前的解决方案。使用TypeScript declare模块的另一种方法如下:- 创建文件my-module.d.ts
declare module 'my-module' {
export default function anyName(arg1: string, arg2: string): MyResponse;
export interface anyName {
string: arg;
}
}
然后作为
import * as my-module from 'my-module';
TypeScript 1.8.2在尝试使用
baseUrl
时出现此错误:错误TS5023:未知的编译器选项“baseUrl”。
并且GitHub问题被标记为2.0里程碑。我猜这实际上并没有变成1.8。@m是的,他们现在把它改成了2.0
declare module 'my-module' {
export default function anyName(arg1: string, arg2: string): MyResponse;
export interface anyName {
string: arg;
}
}
import * as my-module from 'my-module';