TypeScript声明模块

20

我希望在我的 TypeScript 应用程序中创建本地模块,然后通过导入模块来简单地引用任何文件,例如myApp/componentsmyApp/pipes等,而不使用相对路径(../../../MyComponent)。

例如,Angular 2 可以像这样使用。(我还没有找到他们是如何做到的

import {Component} from 'angular2/core';

我该如何实现这种行为?


我创建了一些文件,例如components.tstemplates.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构建告诉我有错误,例如 ...file_path...(4,9): error 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"
    ]
}
2个回答

15
在TypeScript 2.0及以上版本中,tsconfig.json 中有一个baseUrlpaths属性,您可以使用它们。在您的情况下,您需要:
{
    "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的基础上,您可以添加paths。这对您很有用,必须与baseUrl一起使用。在paths中,您可以指定要匹配的模式和要包含在该模式中的文件列表。这在github issue中进行了说明:

"paths": {
    "pattern-1": ["list of substitutions"],
    "pattern-2": ["list of substitutions"],
    ...
    "pattern-N": ["list of substitutions"]
}

请注意,这只会使其编译。我认为您还需要配置SystemJS才能在运行时使其正常工作,这可能需要使用文件并设置路径以指向桶文件。
您可以在github问题中阅读更多相关信息,或阅读我的其他相关答案这里,该答案还显示了TS 2.0之前的解决方案。

TypeScript 1.8.2在尝试使用“baseUrl”时会出现此错误:“error TS5023:未知的编译器选项'baseUrl'。” GitHub问题已标记为2.0里程碑。我猜这实际上并没有进入1.8版本。 - MrHen
1
@MrHen 是的,他们现在将其更改为2.0。 - David Sherret

2

另一种使用TypeScript声明模块的方法如下:

创建一个名为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';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接