我们正在从.net实体创建一个npm模块。但是我无法在我的angular2组件上使用它。
这就是结构模块:在此处输入图片描述
我想从index.d.ts导入(到npm中),我们决定创建一个模块以满足所引用的类型
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:找不到名称“地址”。
我尝试使用导入
import { cio } from 'npm_module_name/index/';
并创建一个像
let testAddress : cio.Address = new cio.Address();
错误:(31,20)TS2694:命名空间``*''没有导出的成员``地址''。
我试图用命名空间替换模块,但是没有用
如何在组件上导入的最佳方法是什么?谢谢
我最近需要这样做,这就是我所做的。
首先,请确保tsconfig.json
对npm软件包使用正确的TypeScript配置();最重要的内容如下所示:
{
"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
文件。在这里,您还可以在发行版中提及您的主文件以及类型定义的位置。下面显示了一个示例(为简洁起见,其中不包括其他信息,例如许可证,存储库等)。
{
"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
如下所示的:
export * from "./dir1/file1";
export * from "./dir1/file2";
export * from "./dir2/file1";
export * from "./dir2/file2";
...
请注意gulp-create-tsindex
扁平化文件夹结构。因此,即使stuffs
位于中dir1/subdir2/somestuffs.ts
,您仍然需要import
使用上述import
语法(import {stuffs} from "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')
)
]);
});
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句