Typescript 1.8模块:从文件夹导入所有文件 [英] Typescript 1.8 modules: import all files from folder

查看:1551
本文介绍了Typescript 1.8模块:从文件夹导入所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Typescript建立一个大型库,其中包含100个单独的ts文件. 以前,我为我的所有类使用了导出模块XXX (以后重命名为 export命名空间XXX ),但是正如书中所说,这不是推荐的方式,我应该改用import

I am building a big library with Typescript with like 100 separate ts files. Previously I used export module XXX (renamed to export namespace XXX later) for all my classes, but as books say, this is not a recommended way, I should use import instead.

所以我尝试导入.效果很好:

So I tried importing. This worked fine:

import * as mylib from "./source/source.ts";

但是由于我有100个文件,所以我不想为所有文件添加这样的行.我希望可以通过 mylib 变量访问所有类.

But as I have 100 files, I don't want to add such a line for all of them. And I want all my classes to be accessible through mylib variable.

所以我尝试了这个:

import * as mylib from "./source/";

但是,一旦执行此操作,我就会得到:找不到模块'./source/'

But as soon as I do this, I get: Cannot find module './source/'

是否可以从一行中包含多个文件的文件夹中导入所有类?

Is there a way to import all the classes from a folder with multiple files with a single line?

推荐答案

tsc提供的两种模块解析策略都不支持这种行为.您需要什么导入声明

Both module resolution strategies that tsc provides don't support such a behavior. What your desired import statement

import * as mylib from "./source/";

实际上要做的是按以下顺序执行检查:

is actually doing is to perform checks in this order:

1. (does package.json have a typings key? If so, import this file)
2. import * as mylib from "./source/index.ts";
3. import * as mylib from "./source/index.tsx";
4. import * as mylib from "./source/index.d.ts";

我假设您在这里使用节点样式的模块分辨率,您可能会使用它,因为这是推荐的方法.查看打字稿文档,以了解有关如何在打字稿中完成模块解析的更多详细信息

I'm assuming you're using node-style module resolution here, which you probably are since it's the recommended way. Check the typescript docs for more details on how module resolution is done in typescript.

通常,您要完成的工作是创建一个index.d.ts文件,该文件用作导出其余模块的入口点. 我以angular2为例: 您常见的angular2导入看起来像这样:

Usually, what you're trying to accomplish is by creating an index.d.ts file, which serves as the entry point from which you're exporting the rest of your modules. I'm using angular2 as an example: Your common angular2 import looks like this:

import { Injectable } from '@angular/core'

core只是位于@angular目录中的目录.就像您的source目录一样.但是,在核心目录中驻留了index.d.ts文件:

core is just a directory that lives inside the @angular directory. Just like your source directory. However, in the core directory resides a index.d.ts file:

/**
 * @module
 * @description
 * Starting point to import all public core APIs.
 */
export * from './src/metadata';
export * from './src/util';
export * from './src/di';
....

这篇关于Typescript 1.8模块:从文件夹导入所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆