NPM — JavaScript 的包管理器

本文主要介紹npm的經常使用命令,以及如何發佈一些經常使用的js模塊化代碼到npm上面方便往後的使用,和舉例如何把一個vue組件打包發佈到npm到最後下載到本地使用的過程。javascript

npm(Node Package Manager)是node的默認模塊管理器,一個命令行下的軟件,用來安裝和管理node模塊,同時也能夠管理其餘開放式的js模塊代碼。npm有一個好處是除了下載須要的模塊外還會幫咱們解決依賴關係,同時下載所依賴的模塊。vue

NPM —— JavaScript 的包管理器

npm help

access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, prune, publish, rb,
    rebuild, repo, restart, root, run, run-script, s, se,
    search, set, shrinkwrap, star, stars, start, stop, t, team,
    test, tst, un, uninstall, unpublish, unstar, up, update, v,
    version, view, whoami
複製代碼

npm help 能夠查看全部可以使用的命令。java

npm經常使用指令

npm install 名字      //該命令用於安裝模塊
npm uninstall 名字    //該命令用於卸載模塊
npm run 名字          //該命令用於執行腳本
複製代碼

如何用npm發佈本身的模塊

咱們全部下載以及發佈的包是存放在這個地址:https://www.npmjs.com/ 咱們發佈一個東西,得要有本身的標識吧,因此得先註冊帳號。node

1.註冊用戶

npm adduser
運行該命令後會須要你依次輸入
Username:
Password:
Email:
複製代碼

2.檢查

接下來是須要檢查一下有沒有註冊成功webpack

npm whoami
複製代碼

3.創建package

npm init
//一路回車
name: (dateFormat) datechange
version: (1.0.0) 
description: change date format
entry point: (index.js) 
test command: 
git repository: https://github.com/shuangmuyingzi/dateFormat.git
keywords: dateformat date datechange
author: lingzi
license: (ISC) 
About to write to /Users/linziying/Downloads/npm/dateFormat/package.json:

{
  "name": "datechange",
  "version": "1.0.0",
  "description": "change date format",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/shuangmuyingzi/dateFormat.git"
  },
  "keywords": [
    "dateformat",
    "date",
    "datechange"
  ],
  "author": "lingzi",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/shuangmuyingzi/dateFormat/issues"
  },
  "homepage": "https://github.com/shuangmuyingzi/dateFormat#readme"
}


Is this ok? (yes) 

複製代碼

而後會在該目錄下多了個package.json文件git

添加簡單的日期轉換格式插件

每次後臺數據接口返回的基本是時間戳,每每須要轉換成經常使用的日期格式。那我就以一個簡單的日期轉換格式小插件爲例。把下面代碼放到package.json文件同級目錄裏。github

date.js

(function(global) {
    var datechange = (function() {
      
      return function (date) {
  
        date = date || new Date;
  
        if(!(date instanceof Date)) {
          date = new Date(date);
        }
  
        if (isNaN(date)) {
          throw TypeError('Invalid date');
        }
        let re = date.getFullYear() + '.' + (date.getMonth()+1) + '.' + date.getDate();
        return re
  
      }
  })()

  if (typeof define === 'function' && define.amd) {
    define(function () {
      return datechange;
    });
  } else if (typeof exports === 'object') {
    module.exports = datechange;
  } else {
    global.datechange = datechange;
  }

})(this);
複製代碼

4.發佈

npm publish 記得在推以前先登陸npm要否則會報錯。若是是再次推送同一個項目記得修改版本號。web

使用

npm install --save-dev datechange
複製代碼
var datechange = require('datechange');
var now = new Date();
var timeStamp = datechange(now);
複製代碼

ORvue-cli

<script type="text/javascript" src='date.js'></script>
	<script type="text/javascript">
		var now = new Date();
		var timeStamp = datechange(1511350834583);
		alert(timeStamp)
	</script>
複製代碼

先安裝後使用,包的名稱爲package.json裏的name屬性。 具體代碼看github: https://github.com/shuangmuyingzi/dateFormatnpm

Vue組件如何上傳到NPM

方式一

用webpack把項目打包成JS文件,而後在package.json的 main導出該JS文件。

建立
  • vue-cli建立vue簡單項目

    vue init webpack-simple load-ling-zi

  • 修改package.json

    1. 修改"private": false

      npm默認建立的項目是私有的,若是要發佈至npm必須將其公開

    2. 添加"main": "dist/build.js"

      經過import loading from 'load-ling-zi'引用該組件時,項目會自動找到node_modules/load-ling-zi/dist/build.js

  • 在src加入組件代碼App.vue, 並建立咱們的導出文件index.js。 在index.js中添加:

    import load from './App.vue'
    export default load
    //global 狀況下 自動安裝
    if (typeof window !== 'undefined' && window.Vue) {
      window.Vue.component('load', load);
    }
    複製代碼
  • 由於最後咱們是打包成一個js文件,因此須要修改一下配置文件webpack.config.js

    由於不是全部使用你組件的人都是經過npm按住和impor的不少人是經過<script>直接引入的,咱們要將libraryTarget改成umd,以及修改入口文件與設置導出文件目錄以及名稱。

    entry: './src/index.js',
         output: {
         path: path.resolve(__dirname, './dist'),
         publicPath: '/dist/',
         filename: 'build.js',
         library: 'load',
         libraryTarget: 'umd',
         umdNamedDefine: true
         },
    複製代碼
  • 最後須要把.gitignore文件裏面的/dist刪除掉要否則上傳時會忽略掉dist打包的文件。

    具體代碼已放到github: https://github.com/shuangmuyingzi/loadingModule/tree/master/load/load-ling-zi

發佈

npm publish,具體參考上面步驟。

應用
  1. Installation
# install dependencies
npm install load-ling-zi -D
複製代碼
  1. Usage
<loading v-if="loading.isShow">
    <span>{{ loading.text }}</span>
</loading>

<script>
    import loading from 'load-ling-zi'
    export default {
        components: {
            loading:loading
        },
        data () {
            return {
                loading:{
                    isShow:true,
                    text:"加載中"
                },   
            }
        }
    }
</script>
複製代碼

方式二

在main裏直接導出Vue組件(.vue文件) 具體代碼看這裏: https://github.com/shuangmuyingzi/loadingModule/tree/master/loading

寫在最後

關於vue組件、插件的實現方式估計還有不少的辦法,本文權當拋磚引玉,水平有限,舉的例子也是比較簡單,一個好的組件也要考慮更多的可配置性以及通用性,數據的可配置,結構的可配置,樣式的可配置等等,es裏面模塊化的寫法也是不少,還有一些直接在<script>引入,因此要考慮如何導出代碼可以知足更多場景的使用。

相關文章
相關標籤/搜索