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

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

相关推荐
海石5 分钟前
去到比北方更北的地方—2025年终总结
前端·ai编程·年终总结
一个懒人懒人12 分钟前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia18 分钟前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全
输出输入20 分钟前
前端核心技术
开发语言·前端
Mintopia25 分钟前
Web 安全与反编译源码下的权限设计:构建前后端一体的信任防线
前端·安全·编译原理
林深现海1 小时前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
Android系统攻城狮1 小时前
鸿蒙系统Openharmony5.1.0系统之解决编译时:Node.js版本不匹配问题(二)
node.js·鸿蒙系统·openharmony·编译问题·5.1
黄诂多1 小时前
APP原生与H5互调Bridge技术原理及基础使用
前端
前端市界1 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生1 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构