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>标签加载。

相关文章
相关标签/搜索