從零發佈一個npm包

如何從零發佈一個npm包

1. 註冊帳號

若是你已經註冊過npm包,能夠跳過去。
輸入命令 npm adduser 根據提示輸入 name、password 、email。
輸完以後,記得去剛剛登記的郵箱激活一下,否則會沒法發佈哦。webpack

tips:web

  • 若是你以前使用的是淘寶源或者公司內部的源,記得切換爲 npm 官方源,命令爲: npm config set registry https://registry.npmjs.org/
  • 若是不肯定是否登陸過npm,能夠使用 npm whoami 查看。

2. 初始化一個簡單的項目

我是參考 webpack 建立library 寫的。
簡單來講就是:npm

  1. mkdir demo && cd demo
  2. npm init -y
  3. npm install --save-dev webpack lodash webpack-cli
  4. 新建一個src 文件夾,添加 index.js 和 ref.json. 他們的內容以下:

// index.jsjson

import _ from 'lodash';
import numRef from './ref.json';

export function numToWord(num) {
  return _.reduce(numRef, (accum, ref) => {
    return ref.num === num ? ref.word : accum;
  }, '');
};

export function wordToNum(word) {
  return _.reduce(numRef, (accum, ref) => {
    return ref.word === word && word.toLowerCase() ? ref.num : accum;
  }, -1);
};

// ref.jsonide

[{
    "num": 1,
    "word": "One"
  }, {
    "num": 2,
    "word": "Two"
  }, {
    "num": 3,
    "word": "Three"
  }, {
    "num": 4,
    "word": "Four"
  }, {
    "num": 5,
    "word": "Five"
  }, {
    "num": 0,
    "word": "Zero"
  }]
  1. 新建一個 webpack-config-js 文件,內容以下:
var path = require('path');
module.exports = {
    entry: { index: './src/index.js' },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'webpack-numbers.js',
        library: 'webpackNumbers',
        libraryTarget: 'umd'
    },
    externals: {
        lodash: {
            commonjs: 'lodash',
            commonjs2: 'lodash',
            amd: 'lodash',
            root: '_'
        }
    }
}
  1. 爲了編譯方便 配置一下 package.json 的build 命令

// scripts 部分函數

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.config.js"
  },

3. 發佈

執行
npm run build
npm publishui

發佈以後能夠在 https://www.npmjs.com/ 查找本身發佈的包。spa

4. 常見報錯

  1. 沒有去郵箱驗證

image.png

  1. 當前的版本號已經發步過,在package.json 裏更新版本號

image.png

  1. 倉庫名字重複,別人已經發布了,更換package.json 裏的name

image.png

使用發佈的npm包

在其餘項目,或者另外的項目
npm install xxx // xxx 是你剛剛發佈的包名字
引入3d

import { numToWord } from 'webpack-number-hqy';

而後就能夠使用 numToWord 函數拉code

相關文章
相關標籤/搜索