[英]Creating a Typescript NPM library
我的项目中有一个models
目录 ( my-models
),其中包含我的应用程序的一些重要的 typescript 类。
我一直在应用程序中毫无问题地使用它,现在我想将其设为 npm package 以便我可以将其导入另一个项目。
这就是我试图做的:
my-models
目录(包含我所有模型和类的目录)my-models
目录中的 npm 链接(包含我所有模型和类的那个)my-models
我遇到的问题是,无论我做什么,我都找不到一种方法来共享我所有的 Typescript 类并在另一个项目中使用它们。 我在编译我的库时遇到了麻烦,然后当我编译它时,我无法在我的客户端项目中导入类。 我收到此错误:
`File '.../services/my-models/index.d.ts' 不是 module.ts(2306)
这是my-models
的 package.json :
{
"name": "my-models",
"version": "0.9.0",
"description": "API Client and models",
"main": "dist/main.js",
"types": "index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"axios": "^0.19.0",
"@types/axios": "^0.14.0"
},
"devDependencies": {
"typescript": "^3.9.5"
}
}
这是我的客户项目中的一个导入,我尝试导入我的一个模型:
import { Student } from 'my-models'
但是等等,我有点让它工作:
import { Student } from 'my-models/dist/main'
为什么? 我在my-models
的 package.json 中说 dist/main.js 是主文件,为什么我不能从“my-models”导入*?
顺便说一句,这是 my-models/dist 目录:
所以不确定我是否做错了什么或如何正确地做。 感谢任何帮助
我使用 Angular CLI 构建 NPM 库,即使它们不是 Angular 项目。 You can just delete the Angular dependencies from the package.json file and you have a world class TypeScript project setup for you with a great test pipeline.
npm install --global @angular/cli
ng new my-lib --create-application=false
cd my-lib
ng generate library my-lib
After you generate the library you can go into the projects/my-lib/src directory open the package.json file and get rid of the Angular dependencies. 现在您有一个空白的 TypeScript 项目。
ng build my-lib
将构建它
ng test my-lib
将运行单元测试
cd 进入 dist/my-lib 文件夹,您可以npm publish
到 npm。
当您可以利用 Angular 团队的工作时,为什么要手动推出 TypeScript 构建?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.