Angular 如何从Typescript上的外部模块导入类
我们正在从.net实体创建一个npm模块。但我不能在angular2组件上使用它 这就是结构模块: 我想从index.d.ts(到npm)导入,我们决定创建一个模块以满足引用的类型Angular 如何从Typescript上的外部模块导入类,angular,typescript,npm,Angular,Typescript,Npm,我们正在从.net实体创建一个npm模块。但我不能在angular2组件上使用它 这就是结构模块: 我想从index.d.ts(到npm)导入,我们决定创建一个模块以满足引用的类型 declare module cio { export class Address { addressLine1: string; addressLine2: string; city: string; state: string; country: string;
declare module cio {
export class Address {
addressLine1: string;
addressLine2: string;
city: string;
state: string;
country: string;
postalCode: string;
}
。
.
}
我尝试使用
import { Address, ... } from 'npm_module_name/index';
import { cio } from 'npm_module_name/index/';
并创建一个类似
let testAddress : Address = new Address();
let testAddress : cio.Address = new cio.Address();
错误:(31,16)TS2304:找不到名称“地址”
我尝试使用
import { Address, ... } from 'npm_module_name/index';
import { cio } from 'npm_module_name/index/';
并创建一个类似
let testAddress : Address = new Address();
let testAddress : cio.Address = new cio.Address();
错误:(31,20)TS2694:命名空间“*”没有导出的成员“地址”
我试图用名称空间替换模块,但没有成功
在我的组件上导入的最佳方式是什么?谢谢我最近需要这样做,以下是我所做的 首先,确保您为npm包使用了正确的TypeScript配置(
tsconfig.json
);最重要的内容如下所示:
{
"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包名作为模块。因此,您可以在使用此软件包时执行以下操作
import {stuffs} from "YourAwesomePackage"
npm模块的名称自然来自您的package.json
文件。在这里,您还可以提到发行版中的主文件以及类型定义的位置。下面显示了一个示例(为简洁起见,不包括许可证、存储库等其他信息)
我选择在我的构建步骤(使用gulp)中生成/index.ts
,它只导出包中的所有内容,为此我使用了。使用此选项,您可以生成一个索引.ts
,如下所示:
export * from "./dir1/file1";
export * from "./dir1/file2";
export * from "./dir2/file1";
export * from "./dir2/file2";
...
请注意,gulpcreate-tIndex
会展平文件夹结构。因此,即使stuff
位于dir1/subdir2/somestuff.ts
中,您仍然需要使用上述import
语法导入它(import{stuff}来自“YourAwesomePackage”
)
使用此方法,最小生成任务如下所示:
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')
)
]);
});
希望这有帮助 你能更具体地说明你尝试了什么以及你会遇到什么错误吗?那将有助于我们帮助你。Thx.包含类的模块必须对包含要导入它的组件的模块可见。它是应用程序模块中导入数组的一部分吗?@DeborahK我在我的帖子中添加了更多信息,谢谢。@CharlesHankey模块已添加到app.module.ts导入数组中。您不需要导出declare模块cio吗?感谢您的帮助,我们决定基于Swagger生成模型