Node.js中package.json与npm

Node.js中package.json与npm

package.json是相当于一个Node.js项目的说明,它包含了这个项目的基本信息,如项目名称,版本号,作者,依赖的包等等。

npm是Node项目的一个包管理工具,可以引入,卸载包等等。

1、首先创建一个项目(文件夹)。

2、在当前目录下,创建package.json。

使用命令:使用该命令时,最好项目名称不是中文(可能会导致一些错误)

npm init

然后根据向导一步一步完成设置:(按回车表示此项为默认项),如果加上参数(npm init -y)表示默认所有配置为默认配置。

D:\NodejsWorkSpace\TestOne\packageANDnpm>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (packageandnpm)  #<--项目名称
version: (1.0.0) 0.0.1         #<--版本号
description: 这是一个描述。     #<--描述
entry point: (main.js)         #<--程序入口
test command:                  #<--测试命令
git repository:                #<--Git地址
keywords:                      #<--关键字(被搜索时)
author: LitongZero             #<--作者名
license: (ISC)                 #<--许可证
About to write to D:\NodejsWorkSpace\TestOne\packageANDnpm\package.json:

{
  "name": "packageandnpm",
  "version": "0.0.1",
  "description": "这是一个描述。",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "LitongZero",
  "license": "ISC"
}


Is this ok? (yes) yes
  • name - 包名。

  • version - 包的版本号。

  • description - 包的描述。

  • homepage - 包的官网 url 。

  • author - 包的作者姓名。

  • contributors - 包的其他贡献者姓名。

  • dependencies - 依赖包列表。如果依赖包没有安装,npm 会自动将依赖包安装在 node_module 目录下。

  • repository - 包代码存放的地方的类型,可以是 git 或 svn,git 可在 Github 上。

  • main - main 字段指定了程序的主入口文件,require('moduleName') 就会加载这个文件。这个字段的默认值是模块根目录下面的 index.js。

    扫描二维码关注公众号,回复: 2757282 查看本文章
  • keywords - 关键字

3、说明依赖的包

在安装依赖包的同时,在命令前加上`--save`

例如:

npm install --save art-template
或
npm install art-template --save
或
npm i -S art-template
       ^为大写S

这时再打开package.json

{
  "name": "packageandnpm",
  "version": "0.0.1",
  "description": "这是一个描述。",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "LitongZero",
  "license": "ISC",
  "dependencies": {
    "art-template": "^4.12.2"
  }
}

发现其中多了“dependencies”项。其中说明了依赖的包,以及版本。这样,如果你不小心删除了项目中的“node_modules”,也可以通过这个来安装之前安装的包。

说明,这个只有在安装的时候加上指定的命令(--save  或 -S)才能保存到“package.json”中,另外,在删除包的时候,也要加上(--save  或 -S)才能删除“dependencies”项中的说明。

猜你喜欢

转载自blog.csdn.net/LitongZero/article/details/81435475