5 分钟 TypeScript NPM 包

2025-06-10

5 分钟 TypeScript NPM 包

介绍

作为开发人员,我们可能想要创建一个新的框架或打包可重用的组件、功能等...
希望作为 JavaScript 开发人员,我们有一个 NPM!

我们可能还会使用TypeScript在 Javascript 之上添加一层安全层,并采用更高级的 OOP 设计

那么我们如何创建一个 NPM 包,使其可供
JavaScript 项目(尤其是 Typescript 项目)使用呢?

让我们去看看我们在Monisnap上是如何做的!

入门

(我假设你已经安装了 NodeJS 和 Typescript)

首先创建一个新文件夹并打开终端选项卡并输入:

npm init -y
Enter fullscreen mode Exit fullscreen mode

这将通过创建带有一些默认选项的 package.json 来初始化你的 npm 包(我们稍后会讨论这个)


tsc --init
Enter fullscreen mode Exit fullscreen mode

这还通过创建 tsconfig.json 来初始化项目以使用 TypeScript,其中包含定义如何处理 TypeScript 代码的重要选项。

现在你应该有这个

替代文本

好吗?下一个!

现在我们可以编写一些代码了:)

创建一个“src”文件夹并在其中创建两个文件“index.ts”和“unicorn.ts”(是的,我喜欢独角兽)

独角兽.ts

export class Unicorn {
  public sayHelloTo(name: string): string {
    return `🦄 Hello ${name} !`;
  }
}
Enter fullscreen mode Exit fullscreen mode

索引.ts

export * from "./unicorn";
Enter fullscreen mode Exit fullscreen mode

替代文本

我们现在需要编辑tsconfig.json(复制/粘贴以下内容)

{
  "compilerOptions": {
    "declaration": true,
    "strictNullChecks": true,
    "target": "es5", 
    "outDir": "dist",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "lib": ["es2015", "dom"],
    "rootDir": "src"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}
Enter fullscreen mode Exit fullscreen mode

让我们介绍一下重要的选项:

  • 声明:它告诉 TypeScript 生成类型(如果我们想要为我们的代码生成一些“自动”文档,这一点很重要
  • target:指定 ES 目标版本(这里我选择 ES5 因为我的目标是 nodeJS)
  • outDir:编译后的文件目标
  • 模块/模块解析:我使用 commonJS/nodeJS 作为 NodeJS 上的模块系统
  • sourceMap:如果您希望源映射能够直接调试 Typescript 代码,这一点很重要
  • rootDir:我们的代码所在的根文件夹。

现在我们可以编辑package.json

{
  "name": "unicorn-says-hello-world",
  "version": "1.0.0",
  "description": "A unicorn that says hello world",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "tsc",
    "prepare": "npm run build"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/monisnap-jason/unicorn-says-hello-world.git"
  },
  "keywords": [],
  "author": "monisnap-jason",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

再次强调重要的选项:

  • name: NPM 上包的名称
  • main:入口点(我们的代码将在 dist 文件夹中编译)
  • 类型:代码类型的路径
  • 文件:我们想要包含在包中的文件
  • 脚本:
    • build: tsc 编译我们的代码
    • 准备:这是一个 NPM 钩子,它在发布到 npm 之前执行一个命令(我们告诉它执行上面的构建命令)
  • 存储库:有关保存包代码的存储库的选项

我们还需要一个.gitignore文件(因为我们不想将某些文件夹包含到我们的存储库中):

\dist
\node_modules
Enter fullscreen mode Exit fullscreen mode

最后,您可以创建README.md来告诉大家如何使用您的包。

我们快完成了!

现在进行最后的润色:

npm publish
Enter fullscreen mode Exit fullscreen mode

您应该在终端输出中看到以下内容:
“+ your-package-name@1.0.0

瞧,你的包已经在NPM上了,
这是我的包,供参考unicorn-says-hello-world

现在,如果我想使用我的全新包,我只需要在新项目或现有项目中安装 npm install unicorn-says-hello-world,然后就可以像这样使用它:

如果您有任何疑问,请在下面发表评论!

祝你一切顺利:)

鏂囩珷鏉ユ簮锛�https://dev.to/monisnap/5-min-typescript-npm-package-4ce4
PREV
💡 Vue Typescript 状态管理:到 2022 年我们可以做得比“isLoading”更好
NEXT
忘掉 Web 开发,成为一名云开发人员吧!☁️