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 分钟前
HTML CSS 第二次笔记
前端·css
灯火不休ᝰ21 分钟前
前端处理pdf文件流,展示pdf
前端·pdf
智践行23 分钟前
Trae开发实战之转盘小程序
前端·trae
最新资讯动态29 分钟前
DialogHub上线OpenHarmony开源社区,高效开发鸿蒙应用弹窗
前端
lvbb6638 分钟前
框架修改思路
前端·javascript·vue.js
树上有只程序猿40 分钟前
Java程序员需要掌握的技术
前端
从零开始学安卓43 分钟前
Kotlin(三) 协程
前端
阿镇吃橙子1 小时前
一些手写及业务场景处理问题汇总
前端·算法·面试
庸俗今天不摸鱼1 小时前
【万字总结】前端全方位性能优化指南(九)——FSP(First Screen Paint)像素级分析、RUM+合成监控、Lighthouse CI
前端·性能优化