1.package.json是什么
package.json是用來管理本地依賴包的一個文件。使用package.json可以帶來很多好處。
它可以作為你項目依賴包的一個說明文檔。
它用來指定你項目中所使用依賴包的版本號。
它可以讓你更方便地和其他開發者來分享你的項目。
2.package.json的組成
package.json文件中必須包含的內容有:
1."name"
1)all lowercase
2)one word, no spaces
3)dashes and underscores allowed
2."version"
1)in the form of x.x.x
2)follows (semver spec)[[https://docs.npmjs.com/getting-started/semantic-versioning](https://docs.npmjs.com/getting-started/semantic-versioning)]
3.創建一個package.json
使用npm提供的初始化工具可以方便地創建一個package.json文件
npm init
然后根據提示填寫對應項目。
- name: defaults to author name unless in a git directory, in which case it will be the name of the repository
- version: always 1.0.0
- main: always index.js
- scripts: by default creates a empty test script
- keywords: empty
- author: whatever you provided the CLI
- license: ISC
- repository: will pull in info from the current directory, if present
- bugs: will pull in info from the current directory, if present
- homepage: will pull in info from the current directory, if present
也可以用初始化命令行來對一些參數進行初始化
> npm set init.author.email "wombat@npmjs.com"
> npm set init.author.name "ag_dubs"
> npm set init.license "MIT"
備注:如果項目中的package.json文件中沒有任何內容,那么npm將會使用README.md中的第一行來代替。package.json文件的描述可以方便別人查閱你的項目所依賴的packages,并且極大地方便你對自己項目的管理。
4.指定依賴包
為了指定你在項目中應用到的依賴包,你需要在packages.json文件中將它們列出來,有以下兩類依賴包需要被列出。
- "dependencies":這里列出你產品的application中需要用到的依賴包;
- "devDependencies":這里列出在開發和測試中所用到的依賴包。
這兩個屬性可以在package.json文件手動進行編輯,也可以在安裝這些包的時候用命令行參數自動將她們添加在文件中。
在"dependencies"中添加一項的命令:
npm install <package_name> --save
在"devDependencies"中添加一項的命令:
npm install <package_name> --save-dev