Node.js && npm

how to Install and Use Node.js and npm (Mac, Windows, Linux)javascript

 

 In order to use almost any development tools based in JavaScript, you'll need to know how to use npm and Node.js. GulpGrunt, and Webpack are a few examples of popular technologies you may have heard of that require a knowledge of the Node ecosystem.css

I find myself writing about this over and over again in the prerequisites of an article I've begun to write. I'd prefer to write one definitive guide to refer to in the future, so here it is.html

Prerequisites

  • Basic command line proficiency. Don't skip this step! If you don't know how to use the command line, you'll be fighting an uphill battle. The provided tutorial has everything you need to know.

Goals

  • Learn what Node.js and npm are
  • Set up Node.js and npm on Windows and Mac

What is Node.js?

JavaScript is a client-side programming language, which means it’s processed in the browser. With the advent of Node.js, JavaScript can also be used as a server-side language.前端

What is npm?

npm doesn't stand for Node Package Manager*, which means it’s the tool to connect to the repository containing all the Node.js programs, plugins, modules and so on.vue

*npm actually does not stand for "Node Package Manager" but essentially that's what it is and does, so most people refer to it that way.java

 

Local vs. Global

This is the most confusing concept to understand at first, so it's important to let this settle in. Traditionally, you're used to globally installing any sort of program or software on your computer. If you want Spotify, you'll download Spotify, and then it will be available to you.node

With npm, you will have some global installs, but mostly everything will be done on a local project basis, meaning you'll have to install everything you need for each project in its own directory. If you want to have a project running Gulp and Sass, you'll create a directory, with a new npm install.python

For future reference, any global installations will have the -g flag.linux

 

Installation on Windows

Installing everything on Windows is a breeze.webpack

Install Node.js and npm

Node.js and npm can be installed from a download link. Go to the Node installation page, and download the Node installer. I have a 64-bit Windows 10 OS, so I chose that one.

Once it's done, you can test to see both node and npm functioning by opening PowerShell (or any shell) and typing node -v and npm -v, which will check the version number.

Create a Project

Navigate to the directory in which you want your project to exist - in my case, sites/node-test.

cd sites/node-test

Now initalize a new project with npm.(建立node.js模塊)

npm init
  • 在項目中引導建立一個package.json文件。
    • 安裝包的信息可保持到項目的package.json文件中,以便後續的其它的項目開發或者他人合做使用,package.json在項目中是必不可少的。
  • 和git的初始化倉庫是否是很像。這樣初始化以後,項目目錄下會自動生成一個package.json文件。
  • 注意的是,npm init命令後,npm會詢問你一系列問題,當你填入答案後纔會正式結束初始化,若是不太想自定義一些關於項目的描述,能夠不敲npm init,而是直接敲npm init --yes
    • 命令行中將會提示 package.json 字段中須要你輸入的值。
      • 名稱(name) 和 版本(version) 這兩個字段是必填的。
      • 你還須要輸入 入口文件字段(main) 字段,默認值是 index.js

First, it will ask for a package name.

node-test

Version number.

1.0.0

Description.

Creating my first "Hello, World!" Node project.

The rest you can just press enter and skip. Now you'll notice we have a package.json file that contains all the information we entered.

package.json
{ "name": "node-test", "version": "1.0.0", "description": "Creating my first \"Hello, World!\" Node project.", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Tania Rascia", "license": "ISC" }

A package.json is a file that contains metadata about the project, and handles the dependencies (additional software and modules) of the project.

在index.js文件中,添加一個函數,做爲 exports對象的一個屬性。這樣,require 此文件以後,這個函數在其餘代碼中就可使用了。

Package.json 屬性說明

  • name - 包名。

  • version - 包的版本號。

  • description - 包的描述。

  • homepage - 包的官網 url 。

  • author - 包的做者姓名。

  • contributors - 包的其餘貢獻者姓名。

  • dependencies - 依賴包列表。若是依賴包沒有安裝,npm 會自動將依賴包安裝在 node_module 目錄下。

  • repository - 包代碼存放的地方的類型,能夠是 git 或 svn,git 可在 Github 上。

  • main - main 字段指定了程序的主入口文件,require('moduleName') 就會加載這個文件。這個字段的默認值是模塊根目錄下面的 index.js。

  • keywords - 關鍵字

Now, we're going to install our first dependency - a very important and useful package called left-pad, which will add white space to the left side of a string, adding up to a number.

For example, writing this:

leftPad('String', 10)

Will output this:

console
String

left-pad is a package on npm, which as we stated previously contains the registry for all publicly available packages.

 

Install dependencies ,下載安裝依賴包

前面有提到初始化項目,可視爲建立node.js模塊的時候,會生成package.json文件。

而咱們的項目顯然會在途中用上不少模塊,這些模塊是不便所有上傳到github倉庫供用戶下載的(github有限制倉庫大小不能超過100M)。且用戶還需本身手動安裝這些依賴包也容易出錯。

爲此,npm提供了很大的便利

To install a dependency with npm, we use the command npm install dependency-name-here. Now, simply running npm install will download the dependency, but it won't save it to the project. Since we've already created our package.json, we'll use the flag --save to install the dependency and add it to package.json.

npm install left-pad --save # 安裝一個本地包,若是加上-g選項則是安裝全局包

有兩種方式用來安裝 npm 包:本地安裝和全局安裝。至於選擇哪一種方式來安裝,取決於咱們如何使用這個包。

  • 若是你本身的模塊依賴於某個包,並經過 Node.js 的 require 加載,那麼你應該選擇本地安裝,這種方式也是 npm install 命令的默認行爲。
  • 若是你想將包做爲一個命令行工具,(好比 grunt CLI),那麼你應該選擇全局安裝

本地安裝和全局安裝區別

  • 本地安裝
    • 1. 將安裝包放在 ./node_modules 下(運行 npm 命令時所在的目錄),若是沒有 node_modules 目錄,會在當前執行 npm 命令的目錄下生成 node_modules 目錄。
    • 2. 能夠經過 require() 來引入本地安裝的包。
  • 全局安裝
    • 1. 將安裝包放在 /usr/local 下或者你 node 的安裝目錄。
    • 2. 能夠直接在命令行裏使用。

若是你但願具有二者功能,則須要在兩個地方安裝它或使用 npm link

As long as you ran this command inside the project directory, it will successfully install the dependency by creating a node_modules directory. It will also create a package-lock.json file, which we can ignore. Finally, it updated our package.json file with a new line.

安裝好以後,express 包就放在了工程目錄下的 node_modules 目錄中,所以在代碼中只須要經過 require('express') 的方式就好,無需指定第三方包路徑。

同理,你在npm中下載別人發佈的項目或模塊後,也須要npm install來安裝好依賴以便運行。

"dependencies": { "left-pad": "^1.1.3" }

Now the project recognizes the left-pad dependency as existing

You can also run npm install --save-dev to specify that the dependency will only be used for development (not production) purposes.

 

卸載模塊

咱們可使用如下命令來卸載 Node.js 模塊。

$ npm uninstall express

卸載後,你能夠到 /node_modules/ 目錄下查看包是否還存在,或者使用如下命令查看:

$ npm ls

 

更新模塊

咱們可使用如下命令更新模塊:

$ npm update express

搜索模塊

使用如下來搜索模塊:

$ npm search express

建立模塊和發佈模塊

建立模塊使用的命令和步驟在前面npm init中己提到。

使用如下命令在 npm 資源庫中註冊用戶(使用郵箱註冊):

$ npm adduser Username: tielemao Password: Email: (this IS public)tieleyumao@gmail.com

用如下命令來發布模塊:

$ npm publish

若是你以上的步驟都操做正確,你就能夠跟其餘模塊同樣使用 npm 來安裝本身發佈的模塊。

版本號

使用NPM下載和發佈代碼時都會接觸到版本號。NPM使用語義版本號來管理代碼,這裏簡單介紹一下。

語義版本號分爲X.Y.Z三位,分別表明主版本號、次版本號和補丁版本號。當代碼變動時,版本號按如下原則更新。

  • 若是隻是修復bug,須要更新Z位。
  • 若是是新增了功能,可是向下兼容,須要更新Y位。
  • 若是有大變更,向下不兼容,須要更新X位。

版本號有了這個保證後,在申明第三方包依賴時,除了可依賴於一個固定版本號外,還可依賴於某個範圍的版本號。例如"argv": "0.0.x"表示依賴於0.0.x系列的最新版argv。

NPM支持的全部版本號範圍指定方式能夠查看官方文檔

使用淘寶 NPM 鏡像

你們都知道國內直接使用 npm 的官方鏡像是很是慢的,這裏推薦使用淘寶 NPM 鏡像。

淘寶 NPM 鏡像是一個完整 npmjs.org 鏡像,能夠用此代替官方版本(只讀),同步頻率目前爲 10分鐘一次,以保證儘可能與官方服務同步。

使用淘寶定製的 cnpm (gzip 壓縮支持) 命令行工具代替默認的 npm:

$ npm install -g cnpm --registry=https://registry.npm.taobao.org

這樣就可使用 cnpm 命令來安裝模塊了:

$ cnpm install [name]

 

Run Node in the terminal

Let's create index.js in the root of our directory. This is everything you should have now:

 

 

 

For future reference, don't bother looking in the node_modules rabbit hole. It will get really overwhelming with bigger projects.

In order to use a dependency, we use require() and put it in a variable, like so:

const leftPad = require('left-pad')

This will be the entirety of our index.js file, in which we require left-pad, run a leftPad()function, and send it to the console.

const leftPad = require('left-pad') // Require left pad const output = leftPad('Hello, World!', 15) // Define output // Send output to the console console.log(output)

Since Node.js is not recognized by the browser, we'll be testing this in the console. In your shell, run the node command followed by the filename in the root of your project.

node index.js

If everything went well, you should have printed Hello, World! to the console, with two spaces on the left.

Hello, World!

Conclusion

In this tutorial, we learned the following:

  • What Node.js is
    • 因爲Node.js平臺是在後端運行JavaScript代碼,因此,必須首先在本機安裝Node環境。
      • 在Windows上安裝時務必選擇所有組件,包括勾選Add to Path
      • node.js是javascript的一種運行環境,是服務器端的javascript的解釋器。
    • Node.js是一個基於Chrome JavaScript運行時創建的平臺, 用於方便地搭建響應速度快、易於擴展的網絡應用。
    • Node.js 使用事件驅動, 非阻塞I/O模型而得以輕量和高效,很是適合在分佈式設備上運行數據密集型的實時應用。
      • Node.js很適合搭建輕量的服務器(應用),因此它又被人稱爲服務器語言,前端中的後端語言。
  • What npm is
    • npm實際上是Node.js的包管理工具(package manager)
      • 爲啥咱們須要一個包管理工具呢?由於咱們在Node.js上開發時,會用到不少別人寫的JavaScript代碼。若是咱們要使用別人寫的某個包,每次都根據名稱搜索一下官方網站,下載代碼,解壓,再使用,很是繁瑣。因而一個集中管理的工具應運而生:你們都把本身開發的模塊打包後放到npm官網上,若是要使用,直接經過npm安裝就能夠直接用,不用管代碼存在哪,應該從哪下載。
      • 更重要的是,若是咱們要使用模塊A,而模塊A又依賴於模塊B,模塊B又依賴於模塊X和模塊Y,npm能夠根據依賴關係,把全部依賴的包都下載下來並管理起來。不然,靠咱們本身手動管理,確定既麻煩又容易出錯
      • npm則是包含在node.js裏面的一個包管理工具,就如同linux中的yum倉庫,rpm包管理;如同python中的pip包管理工具同樣。而這些包管理工具都是予以使用的人們方便,同時解決各類包依賴之間的關係的。
        • 既然npm是包管理工具,那麼它本身也和node.js分開自成一個網站,在npm的網站上面,就如同github,其倉庫中保管了N多的開源項目,有世界上衆多開發者提供的項目。咱們只須要在npm的網站上搜索相關的就能夠找到,而後在線上下載也行,直接在本身的項目中使用命令行安裝也行。
      • npm 由三個獨立的部分組成:

        • npm官方網站(倉庫源):網站 是開發者查找包(package)、設置參數以及管理 npm 使用體驗的主要途徑。
        • 註冊表(registry)(package.json):註冊表 是一個巨大的數據庫,保存了每一個包(package)的信息。
        • 命令行工具 (CLI):CLI 經過命令行或終端運行。開發者經過 CLI 與 npm 打交道。
    • npm已經在Node.js安裝的時候順帶裝好了
      • C:\>npm -v
      • 不過如果想要單獨更新npm時怎麼辦?可使用如下兩個命令進行更新:
        • npm install npm@latest -g 
        • npm install npm@next -g
  • How to install Node.js and npm on Windows or Mac
  • How to make a local project
  • How to install a dependency with npm
  • How to run a file using a node_modules dependency in a shell

If you got lost at any point, view the source on GitHub.

With this knowledge, you're ready to start using Gulp, Grunt, Webpack, Browserify, or anything else that depends on Node.js or npm.

 

相關知識點

前端的構建工具常見的有Grunt、Gulp、Webpack三種,Grunt比較老舊,功能少,更新少,插件少。

 

 

Grunt和全部grunt插件都是基於nodejs來運行的,若是你的電腦上沒有nodejs,就去安裝吧。

前端工程自動化方案更新很快, 學習這些工具,是爲了減輕重複勞動,提升效率。選擇適合本身的方案,而不是在追尋技術的路上迷失了方向。

 Gulp,

gulp是一個自動化構建工具,主要用來設定程序自動處理靜態資源的工做。簡單的說,gulp就是用來打包項目的。

gulp是基於Nodejs的自動任務運行器,它能自動化地完成javascript/sass/less/html/image/css 等文件的的測試、檢查、合併、壓縮、格式化、瀏覽器自動刷新、部署文件生成,並監聽文件在改動後重復指定的這些步驟。

使用Gulp的優點就是利用流的方式進行文件的處理,使用管道(pipe)思想,前一級的輸出,直接變成後一級的輸入,經過管道將多個任務和操做鏈接起來,所以只有一次I/O的過程,流程更清晰,更純粹。Gulp去除了中間文件,只將最後的輸出寫入磁盤,整個過程所以變得更快。

使用Gulp,能夠避免瀏覽器緩存機制,性能優化(文件合併,減小http請求;文件壓縮)以及效率提高(自動添加CSS3前綴;代碼分析檢查)

 

gulp的插件使用

  同Grunt通常,gulp也有插件庫,具體有興趣開發gulp插件的,能夠看看 http://www.gulpjs.com.cn/docs/writing-a-plugin/

 

 Grunt,

前端自動化小工具,基於任務的命令行構建工具

自備node環境(>0.8.0), npm包管理

通常須要在你的項目中添加兩份文件:package.json 和 Gruntfile

Grunt的基本使用也就如上所示,比較簡單,更多能夠參考Grunt的插件庫,好比 contrib-jshint js代碼檢查等插件的使用

Webpack,

Webpack是一個模塊打包的工具,它的做用是把互相依賴的模塊處理成靜態資源。

webpack的進階使用 之 加載器

何謂加載器?加載器是對你的應用的源文件進行轉換的工具。

不一樣類型的文件有不一樣的加載器,好比jsx,es6要用到babel-loader,

加載css要用到css-loader,加載html要用到html-loader,以及 vue-loader,css-loader 等等. 

全部的loader都放在module下面的loaders裏邊.一般有如下內容:

  1. test:是對該類文件的正則表達式,用來判斷採用這個loader的條件 

  2. exclude是排除的目錄,好比node_modules中的文件,一般都是編譯好的js,能夠直接加載,所以爲了優化打包速度,能夠排除。做爲優化手段它不是必須的 

  3. loader: 加載器的名稱,每個加載器都有屬於它本身的用法,具體要參考官方說明

  4. query: 傳遞給加載器的附加參數或配置信息,有些也能夠經過在根目錄下生成特殊的文件來單獨配置,好比.babelrc 

  以上只是稍微講了webpack的基礎使用,更多使用方法 能夠查看官方文檔

Browserify

 一個前端構建工具,只能構建JavaScript文件。

可讓你使用相似於 node 的 require() 的方式來組織瀏覽器端的Javascript代碼,經過預編譯讓前端Javascript能夠直接使用 Node NPM 安裝的一些庫。

Browserify是一個供瀏覽器環境使用的模塊打包工具,像在node環境同樣,也是經過require('modules')來組織模塊之間的引用和依賴,既能夠引用npm中的模塊,也能夠引用本身寫的模塊,而後打包成js文件,再在頁面中經過<script>標籤加載。

相關文章
相關標籤/搜索