如何从 Typescript 上的外部模块导入类 [英] How can I import classes from external module on Typescript

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

问题描述

我们正在从 .net 实体创建一个 npm 模块.但我无法在我的 angular2 组件上使用它.

We are creating an npm module from .net entities. But I'm not able to use it on my angular2 component.

这是结构模块:在此处输入图片描述

我想从 index.d.ts 导入(到 npm 中)我们决定创建一个模块以满足引用的类型

I want to import from index.d.ts (into npm) we decide to create a module in order to satisfy the types referenced

declare module cio {
export class Address {
    addressLine1: string;
    addressLine2: string;
    city: string;
    state: string;
    country: string;
    postalCode: string;
}

...

declare module cio {
 export class Business {
    id: string;
    typeName: string;
    createdDate: Date;
    lastModifiedDate: Date;
    createdBy: string;
    lastModifiedBy: string;
    isTest: boolean;
    isDeleted: boolean;
    taxId: string;
    businessType: BusinessType;
    businessName: string;
    address: Address;
    phone: string;
    mobile: string;
    fax: string;
    email: string;
}
enum BusinessType {
    Individual = 1,
    Company = 2,
}

}

我尝试使用

import { Address, ... } from 'npm_module_name/index';

并创建一个像

let testAddress : Address = new Address();

错误:(31, 16) TS2304:找不到名称地址".

Error:(31, 16) TS2304:Cannot find name 'Address'.

我尝试使用

import { cio } from 'npm_module_name/index/';

并创建一个像

let testAddress : cio.Address = new cio.Address();

错误:(31, 20) TS2694:命名空间*"没有导出成员地址".

Error:(31, 20) TS2694:Namespace ''*'' has no exported member 'Address'.

我尝试通过命名空间替换模块,但没有成功

I tried to replace module by namespace but didn't work

在我的组件上导入的最佳方式是什么?谢谢

How is the best way to import on my component? Thanks

推荐答案

我最近需要这样做,这就是我所做的.

I recently had the need to do this, and here is what I have done.

首先,确保您为 npm 包使用了正确的 TypeScript 配置(tsconfig.json);最重要的内容如下所示:

First of all, make sure you are using the correct TypeScript configuration (tsconfig.json) for npm package; most important stuffs are shown below:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "declaration": true, // this is needed to generate the type definitions (*.d.ts)
        "moduleResolution": "node",
        "sourceMap": true,
        "lib": ["es6", "es2017", "dom"]
    }
}

接下来的想法是使用 npm 包名作为模块.因此,您可以在使用此包时执行以下操作.

Next, the idea is to use the npm package name as module. So you can do something like following while using this package.

import {stuffs} from "YourAwesomePackage"

npm 模块的名称自然来自您的 package.json 文件.在那里,您还可以在发行版中提及您的主文件以及您的类型定义的位置.下面显示了一个示例(为简洁起见,这不包括其他信息,例如许可证、存储库等).

The name of the npm module comes naturally from you package.json file. There you can also mention your main file in the distribution as well as the location of your type definitions. An example is shown below (this does not include other information such as licences, repository etc. for brevity).

{
  "name": "YourAwesomePackage",        // this is your npm package name.
  "version": "2.0.0",                  // version is needed to publish
  "main": "dist/index.js",             // Your main script.
  "typings": "dist/definitions/index", // location of your type definitions
  "typescript": {
    "definition": "dist/definitions/index"
  }
}

我选择在我的构建步骤中生成 ./index.ts(使用 gulp),它只是从我的包中导出所有内容,为此我使用了 gulp-create-tsindex.使用它,您可以生成一个 index.ts,如下所示:

I chose to generate the ./index.ts in my build step (using gulp) that just exports everything from my package, and for this I have used gulp-create-tsindex. Using this you can generate a index.ts which looks like follows:

export * from "./dir1/file1";
export * from "./dir1/file2";
export * from "./dir2/file1";
export * from "./dir2/file2";
...

请注意,gulp-create-tsindex 会扁平化文件夹结构.因此,即使 stuffsdir1/subdir2/somestuffs.ts 中,您仍然需要使用上面提到的 import import 语法(import {stuffs} from "YourAwesomePackage").

Note that gulp-create-tsindex flattens the folder structure. Thus, even if stuffs is in dir1/subdir2/somestuffs.ts, you still need to import it using the above mentioned import syntax (import {stuffs} from "YourAwesomePackage").

使用这个最小的构建任务如下所示:

Using this a minimal build task looks as follows:

const ts = require("gulp-typescript");
const tsProject = ts.createProject("path/to/tsconfig");
const tsindex = require('gulp-create-tsindex');
const merge = require('merge2');

gulp.task("build-ts", function() {

    const tsResult = tsProject.src()
        .pipe(tsindex('path/to/src/folder/index.ts')) // location of your new index.ts file
        .pipe(tsProject());

    return merge([
        tsResult.dts.pipe(gulp.dest('path/to/dist/folder/definitions')), //location of your type definitions (don't use a separate 'definitions' folder if you don't like it.
        tsResult.js.pipe(
            gulp.dest('path/to/dist/folder')
        )
    ]);
});

希望这会有所帮助.

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

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