天天看點

釋出一個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) [email protected]
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: [email protected]
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
+ [email protected]
           
  • 對于私有包和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

繼續閱讀