快速搭建 npm 私有仓库

快速搭建 npm 私有仓库

* 工具:Verdaccio

  • 安装 npm i verdaccio -g

  • 启动 verdaccio

#添加用户
npm adduser --registry=xxx
# 登录
npm login --registry=xxx 
# 发布
npm publish --registry=xx

创建一个包:storage ,结构如下

#package.json

{
  "name": "storage", 
  "version": "1.0.3", //包的版本,发新包记得手动修改
  "description": "",
  "main": "./dist/storage.umd.js", // 需了解 umd esm amd 等模块
  "module": "'./dist/storage.es.js", 
  "files": [
    "dist",
    "types"
  ],
  "typings": "./types/main.d.ts", //类型声明文件
  "exports": {
    ".": {
      "default": "./dist/storage.umd.js",
      "import": "./dist/storage.es.js",
      "require": "./dist/storage.umd.js"
    }
  },
  "scripts": {
    "build": "vite build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^18.0.3",
    "typescript": "^4.7.4",
    "vite": "^2.9.13"
  }
}

# vite.config.ts 
//打包 lib 库
import { defineConfig } from 'vite';
import * as path from 'path';

export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, './src/main.ts'),
      name: 'storage',
      fileName: (format) => `storage.${format}.js`,
    },
  },
});

#main.ts
import local from './localStorage';
import session from './sessionStorage';
export { local, session };

#localStorage
export default {
  getItem: (key) => {
    return localStorage.getItem(key);
  },
  setItem: (key, value) => {
    return localStorage.setItem(key, value);
  },
};

#sessionStorage
export default {
  getItem: (key) => {
    return sessionStorage.getItem(key);
  },
  setItem: (key, value) => {
    return sessionStorage.setItem(key, value);
  },
};

#types/main.d.ts 类型声明文件,最好打进依赖包里面,避免使用者需实现声明
declare module 'storage' {
  interface SType {
    getItem: (key: string) => string | null;
    setItem: <T>(key: string, value: T) => void;
  }
  interface storageType {
    local: SType;
    session: SType;
  }
  const storage: storageType;
  export = storage;
}
打包&发布
npm run build
npm publish --registry=xxx
使用包
npm install storage --registry=xxx

or

.npmrc 中指定该包的镜像源

# .npmrc 文件可配置如下
storage:registry=http://localhost:4873/
registry=https://registry.npm.taobao.org/

效果如下:

posted @ 2022-07-06 22:18  zcookies  阅读(837)  评论(0编辑  收藏  举报