NodeJS的NPM打包记录

关于NPM打包,注意此处是在后端项目的NPM打包,使用也是给后端项目进行使用。

为什么要进行打包

因为提供的公共方法或者是每次更改以后重新生成的大量代码可以使用NPM打包的方式进行管理,同时公司中建设一个私有NPM仓库方便使用。

关于公司的私有仓库选择

可以选择阿里云的云效平台或者其他,本文主要介绍打包流程,不关注仓库建设。

重点介绍打包流程

默认是一个空目录下或者是只有你需要打包的代码,没有其他

比如

myNpm

-src

--myApp.ts

1. 设置package.json文件

复制代码
npm init -y

初始化npm设置,其中有一个name字段是发包的包名字段,还有version字段就是以后的包的版本。

初始化完成以后会有一个pkg.json文件的生成

我的json文件配置如下,大家可以照着我的来:

复制代码
{
  "name": "myNPM",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc",
    "release": "tsc && npm publish"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "dependencies": {
    "antlr4": "^4.13.1"
  }
}

2. 设置tsconfig.json

终端执行指令

复制代码
tsc init

生成tsconfig.json文件

设置如下:

复制代码
{
  "compilerOptions": {
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "declaration": true
  }
}

关键设置:

declaration:true 设置自动生成说明文件

outDir: 设置输出目录为dist

3. 自定义index.ts文件

将需要在以后的项目中使用的类、方法等在此文件中导出。

踩坑:

default class导出多个的时候需要用export {***, ***} 这样的形式,如果直接导出,如export * from 'path' 会存在问题module的识别问题

4. 后续发布和使用

完成npm login登录以后,进行检查版本号和name发布即可

复制代码
npm publish

使用时直接引入使用即可。

相关推荐
wuhen_n1 小时前
TypeScript 强力护航:PropType 与组件事件类型的声明
前端·javascript·vue.js
wuhen_n1 小时前
组件设计原则:如何设计一个高内聚、低耦合的 Vue 组件
前端·javascript·vue.js
Moment13 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
IT_陈寒14 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
小时前端15 小时前
React性能优化的完整方法论,附赠大厂面试通关技巧
前端·react.js
Nicko15 小时前
Jetpack Compose BOM 2026.02.01 解读与升级指南
前端
小蜜蜂dry15 小时前
nestjs学习 - 控制器、提供者、模块
前端·node.js·nestjs
优秀稳妥的JiaJi15 小时前
基于腾讯地图实现电子围栏绘制与校验
前端·vue.js·前端框架
San3016 小时前
手写 Mini Cursor:基于 Node.js 与 LangChain 的开发实战
langchain·node.js·agent
前端开发呀16 小时前
从 qiankun(乾坤) 迁移到 Module Federation(模块联邦),对MF只能说相见恨晚!
前端