npm包发布流程

npm 发布包流程

背景:假设你写了一些 js 方法想打包发布
参考:https://www.youtube.com/watch?v=xnfdm-s8adI、

1. 初始化环境

mkdir methodjs
cd methodjs
npm init -y

# 安装依赖包
npm i -D tsup@5 typescript@4 
# 这是 node < 14 时的兼容版本,否则安装最新的即可;tsup用于编译打包ts代码

# 确保用的是npm地址
npm config set registry https://registry.npmjs.org

2. 配置文件

- package.json      // 包的信息
- tsconfig.json     // ts编译配置
- tsup.config.ts    // tsup打包配置
- .npmignore        // 列举发布包时不想包含的文件
- .gitignore        // (可选)列举上库时不想包含的文件

  • package.json

    {
       "name": "@sanhuamao1/methodjs", // 包名
       "version": "1.0.0",
       "description": "",
       "main": "./dist/index.js", // 当用户尝试通过 require() 引入时,Node.js 会默认使用这个文件
       "module": "./dist/index.mjs", // 当用户使用 ES 模块导入语法来引入时,Node.js 会使用这个文件
       "types": "./dist/index.d.ts", // 指定类型声明文件的位置
       "homepage": "xxx", // 自定义仓库主页地址
       "repository": {
          "url": "xxx" // 自定义仓库地址
       },
       "scripts": {
          "build": "tsup" // 使用tsup打包源码,让它分别打包成cjs和esm格式,下面有配置说明
       },
       "keywords": [], // 关键词,在npm搜索时输入什么关键词能搜到这个包
       "author": "",
       "license": "MIT",
       "devDependencies": {
          "tsup": "^5.12.9",
          "typescript": "^4.9.5"
       }
    }
    
  • tsconfig.json

    {
       "compilerOptions": {
          "strict": true,
          "noImplicitAny": true, // 禁止在没有类型注解的情况下使用 'any' 类型
          "strictNullChecks": true, // 严格检查 null 和 undefined 的类型,不允许将 null 和 undefined 赋值给非 void 类型的变量
          "target": "ES2022",
          "moduleResolution": "Node", // 使用 Node.js 的模块解析策略
          "module": "CommonJS", // 将代码生成为 CommonJS 模块,适用于 Node.js 环境
          "declaration": true, // 生成相应的 '.d.ts' 声明文件
          "isolatedModules": true, // 将每个文件作为隔离的模块,不进行项目范围内的类型检查
          "noEmit": true, // 不要生成输出文件(例如在隔离模块模式下,不生成声明文件)
          "outDir": "dist" // 指定输出文件夹,编译后的文件将放置在这里
       },
       "include": ["src"],
       "exclude": ["node_modules"]
    }
    
  • tsup.config.ts

    import tsup from 'tsup';
    // 最新版本是导入方式是: import { defineConfig } from 'tsup'
    
    export default tsup.defineConfig({
       format: ['cjs', 'esm'], // 打包为cjs 、esm 格式
       entry: ['./src/index.ts'],
       dts: true, // 生成类型声明文件
       shims: true, // 为 Node.js 核心模块生成 polyfill,在浏览器环境中,也可以使用 require 和 module.exports
       skipNodeModulesBundle: true, // 跳过对 node_modules 中的依赖进行打包
       clean: true,
    });
    
  • .npmignore

    /src
    /node_modules
    
    tsconfig.json
    tsup.config.ts
    
  • .gitignore

    /dist
    /node_modules
    

3. 创建要发布的内容

根据个人喜好创建结构

- src
    - browser
        - download.ts  // 假设这是我想发布的方法
        - index.ts     
        - types.ts
    - index.ts
// src/browser/types.ts

export type DownloadMediaProps = {
   url: string;
   fileName?: string;
};
// src/browser/download.ts

import { DownloadMediaProps } from './types';

const downloadMedia = ({ url, fileName }: DownloadMediaProps) => {
   fetch(url)
      .then((response) => response.blob())
      .then((blob) => {
         const blobUrl = URL.createObjectURL(blob);
         const aElement = document.createElement('a');
         aElement.style.display = 'none';
         aElement.href = blobUrl;
         aElement.download = fileName || url.slice(url.lastIndexOf('/') + 1);
         document.body.appendChild(aElement);
         aElement.click();
         document.body.removeChild(aElement);
      });
};

export { downloadMedia };
// src/browser/index.ts

export * from './types'
export * from './download'
// src/index.ts

export * from './browser'

// 随便写一个方便测试的
export const test = () => {
    console.log('test')
}

4. 编译打包

npm run build

之后会在根目录中生成dist文件夹,里面是编译打包好的内容

5. 本地测试(可选)

  • 在包的根目录下创建链接
    cd path/to/your-package
    npm link
    
  • 在另一个项目中,使用该链接
    cd path/to/your-project
    npm link your-package-name  # 例:npm link @sanhuamao1/methodjs
    
  • 进行测试
    // path/to/your-project/index.js
    
    const { test } = require('@sanhuamao1/methodjs')
    test()
    
    node index.js
    

6. 发布包

  • 确保在npm中创建了账号
  • 登录
    npm login
    
  • 发布
    npm publish # 发布私有包
    npm publish --access=public # 发布公共包
    
posted @ 2024-07-29 15:09  sanhuamao  阅读(27)  评论(0编辑  收藏  举报