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

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

相关推荐
小高0071 分钟前
🤔Proxy 到底比 defineProperty 强在哪?为什么今天还在聊 Proxy?
前端·javascript·vue.js
哔哩哔哩技术2 分钟前
VibeCut - 智能剪辑探索与实现
前端
用户904706683573 分钟前
在uniapp Vue3版本中,如何解决,web/H5网页浏览器跨域的问题
前端
RaidenLiu26 分钟前
告别繁琐:用 Signals 优雅处理 Flutter 异步状态
前端·flutter·前端框架
星链引擎29 分钟前
面向API开发者的智能聊天机器人解析
前端
前端Hardy30 分钟前
HTML&CSS&JS:纯前端图片打码神器:自定义强度 + 区域缩放,无需安装
前端·javascript·css
道可到36 分钟前
35 岁程序员的绝地求生计划:你准备好了吗?
前端·后端·面试
道可到1 小时前
国内最难入职的 IT 公司排行:你敢挑战哪一家?
前端·后端·面试
jnpfsoft1 小时前
低代码应用菜单避坑指南:新建 / 删除 / 导入全流程,路由重复再也不怕!
前端·低代码
Keepreal4961 小时前
word文件预览实现
前端·javascript·react.js