發佈一個npm包

1.npm 是什麼?

npm是隨同NodeJS一起安裝的包管理工具,能解決NodeJS代碼部署上的很多問題,常見的使用場景有以下幾種:

  • 允許用戶從npm服務器下載別人編寫的第三方包到本地使用。
  • 允許用戶從npm服務器下載並安裝別人編寫的命令行程序到本地使用。
  • 允許用戶將自己編寫的包或命令行程序上傳到npm服務器供別人使用。

由於新版的Nodejs已經集成了npm,所以之前npm也一併安裝好了。同樣可以通過輸入 npm -v 來測試是否成功安裝。

2.創建一個node模塊

1.初始化npm

新建一個 01-publish-npm 項目

`-- 01-publish-npm
    |-- 
    `-- 

在項目的根目錄下執行:

npm init -y  # 初始化npm, -y 自動新建一個package.json文件

此時目錄結構 :

`-- 01-publish-npm
    |-- 
    `-- package.json

修改一下 package.json 文件的name, author 和 description 配置

name version main author 必填

{
  "name": "js-common-util",
  "version": "1.0.0",
  "description": "發佈一個npm包教程",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "liujun",
  "license": "ISC"
}

name 字段是指定發佈包的名稱,必須是小寫和一個單詞,並且可以包含連字符和下劃線。

version 字段的形式必須是x.x。並遵循語義版本控制

main 字段當另一個應用程序需要您的模塊時加載的文件的名稱。默認名稱是index.js

package.json更多配置說明

https://www.cnblogs.com/tzyy/p/5193811.html#_h1_4

2.新建node模塊

新建一個 index.js 文件

此時目錄結構 :

`-- 01-publish-npm
    |-- 01-發佈npm包教程.md
    |-- index.js
    `-- package.json

編寫 node 模塊( index.js的代碼 )

/**
 * 1.獲取文件類型:後綴名(小寫)
 * @param {*} url xxx.jpg / https://www.baidu.com/img/bd_logo1.png
 * @return { httpType: '', suffix: '.jpg' } / { httpType: 'http', suffix: '.png' }
 */
var getFileType = function(url) {
  var httpType = "";
  var suffix = "";
  if (url != null && url.length > 0) {
    var lasindex = url.lastIndexOf(".");
    if (/^(http:|https:)/.test(url)) {
      httpType = "http";
    }
    if (lasindex > -1) {
      suffix = url.substr(url.lastIndexOf(".")).toLowerCase();
    }
  }
  // 返回協議 和 後綴名(小寫)
  return { httpType, suffix };
};
// console.log(getFileType('xxx.jpg'))
// console.log(getFileType('https://www.baidu.com/img/bd_logo1.png'))


/**
 * 2.隨機生成不重複的id
 * @param {} randomLength 生成的長度(默認返回8個)
 */
var genNonDuplicateID = function(randomLength = 8) {
  var id =Math.random()
        .toString()
        // 8個隨機數 + 時間戳
        .substr(2, randomLength) + Date.now()
  return id;
};
// console.log(genNonDuplicateID()) //  76717640 1578386034095


/**
 * 3.判斷是否是合法的url
 */
var isUrl= function(path) {
  var Expression=/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
  var objExp=new RegExp(Expression);
  if(objExp.test(path)==true){
    return true;
  }else{
    return false;
  }
}
// console.log(isUrl('https://www.baidu.com/img/bd_logo1.png?where=super&time=1578386034095')) // true
// console.log(isUrl('http:/www.baidu.com/img/bd_logo1.png?where=super&time=1578386034095')) // false

/**
 * 4.將url中的參數轉成 Object 對象
 * @param {*} url https://www.baidu.com/img/bd_logo1.png?where=super&time=1578386034095
 * @return { where: 'super', time: '1578386034095' }
 */
var parseQueryString = function(url) {
  if (isUrl(url)) {
    var searchurl = url.split("?");
    url = searchurl.length > 1 ? "?" + searchurl[1] : searchurl[0];
  }
  var reg_url = /^\?([\w\W]+)$/;
  var reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
    arr_url = reg_url.exec(url),
    ret = {};
  if (arr_url && arr_url[1]) {
    var str_para = arr_url[1],
      result;
    while ((result = reg_para.exec(str_para)) != null) {
      ret[result[1]] = result[2];
    }
  }
  return ret;
};
// console.log(parseQueryString('https://www.baidu.com/img/bd_logo1.png?where=super&time=1578386034095'))

module.exports = {
  getFileType,
  genNonDuplicateID,
  isUrl,
  parseQueryString
}

node 模塊更多說明

3.把node模塊發佈到npm服務器

1.註冊npm賬號

註冊地址 : https://www.npmjs.com/signup (註冊後要在郵箱驗證)

官方文檔教程:https://docs.npmjs.com/creating-a-new-npm-user-account

2.發佈node模塊

1.登錄npm

進入項目的根目錄執行:npm login

PS F:\blog\npm\01-publish-npm> npm login
Username:
Username: liujunb
Password:
Email: (this IS public) liujun2son@163.com
Logged in as liujunb on http://registry.npmjs.org/.

如果是: Logged in as liujunb on https://registry.npm.taobao.org/.

需要執行:npm config set registry http://registry.npmjs.org

2.執行發佈命令

PS F:\blog\npm\01-publish-npm> npm publish
npm notice
npm notice package: js-pub-npm-util@1.0.0
npm notice === Tarball Contents ===
npm notice 260B  package.json
npm notice 2.4kB index.js
npm notice === Tarball Details ===
npm notice name:          js-pub-npm-util
npm notice version:       1.0.0
npm notice package size:  2.2 kB
npm notice unpacked size: 6.8 kB
npm notice shasum:        a45300189535edd7d32ba1f10d2d516d6f2704e0
npm notice integrity:     sha512-6Md4FG5KSJL3M[...]iAUTd8bBssRfg==
npm notice total files:   2
npm notice
+ js-pub-npm-util@1.0.0
  • 對於私有包和unscoped未限定作用域的包,使用npm發佈: npm publish
  • 對於scoped 限定作用域的公共包: npm publish --access public

發佈過程會把整個目錄發佈,不想發佈的內容模塊,
可以通過 .gitignore.npmignore 文件忽略

3.查看是否已發佈成功

發佈成功之後可以去 npm 官網查看是否已經存在( https://www.npmjs.com/package/已發佈的包名 )

npm 發佈更多說明

發佈unscoped 和 scoped包

4.如何使用已發佈的npm模塊?

新建一個 test 項目

`-- test 
    |--
    `-- 

在項目根目錄執行:

npm init -y
npm install js-pub-npm-util

此時項目的目錄結構:

`-- test
    |-- 
    |-- node_modules
    |   `-- js-pub-npm-util
    |       |-- index.js
    |       `-- package.json
    |-- package-lock.json
    `-- package.json

node_modules -> js-pub-npm-util -> index.js 中的代碼和提交的代碼一模一樣

在項目根目錄新建 index.js 文件

var commonUtils = require('js-pub-npm-util')
console.log(commonUtils.genNonDuplicateID())

在本項目根目錄執行 node index.js 發現代碼已經執行。( 該模塊不支持在瀏覽器中使用,瀏覽器不兼容module.exports模塊化 )

注意:

當本項目需要安裝多個 node 模塊時,跟模塊的安裝順序無關

1. require () 引入的僅僅是第一層 node_modules的庫,不會引入node_modules 中 node_modules 的庫

var commonUtils = require('js-pub-npm-util')

2. 如果本項目依賴js-pub-npm-util庫,本項目的第三方庫也引用了js-pub-npm-util 庫?

  1. 如果js-pub-npm-util 庫 版本號相同,第一層node_modules只存在一個js-pub-npm-util 庫,

    第三方庫雖然也同時依賴,但是它的node_modules不會存在js-pub-npm-util

  2. 如果版本號不相同,第一層node_modules只存在一個js-pub-npm-util庫,

    第三方庫的node_modules也存在一個js-pub-npm-util庫,它們版本號不一樣

3. 如果本項目安裝第三方庫時,如果第三方庫有依賴其它庫。

  1. 如果第三方庫依賴的庫在本項目沒用使用,默認會把第三方庫和其依賴的庫安裝在第一層node_modules

  2. 如果第三方庫依賴的庫在本項目也有使用並且版本號一樣,默認會把第三方庫和其依賴的庫安裝在第一層node_modules

  3. 如果第三方庫依賴的庫在本項目也有使用並且版本號不一樣,默認會把第三方庫安裝在第一層node_modules中,第三方庫依賴的庫安裝在第三方庫的node_modules

4. 其實第三方庫之間也可以隨意使用本項目中第一層 node_modules 的庫

5.更新node模塊併發布

1.更新 package.json 文件 中的版本號

2.重新執行:

npm login
npm publish

6.刪除已發佈的npm包

npm unpublish xxxxxx --force

更多的 npm 命令:

Action CLI command
Log in to npm npm login
Change profile settings (including your password) npm profile set
Change 2FA modes for your user account npm profile enable-2fa auth-only
Disable 2FA for your user account npm profile disable-2fa
Create tokens npm token create
Revoke tokens npm token revoke
Publish packages npm publish
Unpublish packages npm unpublish
Deprecate packages npm deprecate
Change package visibility npm access public/restricted
Change user and team package access npm access grant/revoke
Change package 2FA requirements N/A
發佈了106 篇原創文章 · 獲贊 93 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章