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

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

相关推荐
火山引擎和TA的超级拍档们5 小时前
产品情报局 11 | AI 数据湖 LAS:打造大模型时代多模态数据底座
前端·后端
JavaGuide6 小时前
Gemini 真的变强了,写代码做视频的能力接近 Claude Opus5.5 了!
前端·ai编程
niceyayale6 小时前
WebRTC 延迟怎么调试:从 ICE 到 jitter buffer 的六个观测点
前端
aleimu6 小时前
Windows 11 右键打开 Cmder 2.0:从找不到菜单到默认使用 Cmder
前端·人工智能·后端
tryCbest6 小时前
Vue系列——第 20 篇:Vue Router 4——路由管理完全指南(上)
前端·javascript·vue.js
feixing_fx6 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
一条破秋裤6 小时前
【1115】【多线程】【笔记】
前端·chrome·笔记
黑十6 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
Funlang6 小时前
在 Windows 95 上写前端
前端·javascript·windows
cidy_987 小时前
python第7课. 输入与输出
前端