Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

选择 dependencies 还是 devDependencies ? #3

Open
liuyib opened this issue Feb 20, 2019 · 0 comments
Open

选择 dependencies 还是 devDependencies ? #3

liuyib opened this issue Feb 20, 2019 · 0 comments
Labels
npm📦 JavaScript 包管理工具 - npm

Comments

@liuyib
Copy link
Owner

liuyib commented Feb 20, 2019

terminal

前言

想象一下,你使用 React 创建了一个网站,并且将代码推送到了 github 上,当然你已经将 node_modules 添加到了 .gitignore 文件中,因为你是一个聪明的开发人员。但是,当你尝试在其他电脑上开发这个项目,并运行它时,emmm...并不能运行是吧?因为你使用了 React,它安装在 node_modules 中,但是你没有把它推送到远程库。所以,现在你需要执行一个神奇的命令:

npm install

执行这个命令之后,电脑会自动安装你的项目运行时所需要的依赖项。具体安装哪些依赖,要取决于 package.json 文件里的 dependenciesdevDependencies。但这两个选项,到底有什么区别,总会引人思考。

探究

简单的来说他们的作用分别是:

  • dependencies - 用于生产环境
  • devDependencies - 用于开发环境。

换一种说法:

  • dependencies - 是项目运行时需要的依赖,如果没有,项目跑不起来。例如:React,Redux,Express,Axios,Vue,JQuery...
  • devDependencies - 只是开发的时候所需要的,开发完成后就不需要了。例如:Babel,ESLint,测试框架(如:Chai,Mocha)等...

rollup.js 官方文档 中有句话说的很好:

image

实际上,如果只是做项目的话,这两种并没有什么区别。比如,将 React 放在 devDependencies 下,项目也是可以跑起来的(因为你的电脑上存在 React 依赖),所以 生产环境开发环境 似乎更像是一种建议,那么那么它们实际的区别在哪里呢?

区别

执行 npm install 时,会安装 dependenciesdevDependencies 下的依赖包。但是如果这些依赖包里仍存在依赖,那么只会安装 dependencies 里的。

举个栗子:

package A
  - dependencies
    B
  - devDependencies
    C

package D
  - dependencies
    E
  - devDependencies
    A

有两个包,它们的依赖情况如上。然后将 D 下载到本地,并进行 npm install 操作,所以 D 中的 E、A都会被下载,而 A 中有 dependencies 依赖即 B,所以 B 会被下载。同样的假如 E 中有 dependencies 依赖,那么这个依赖也会被下载。而 A 和 E 中的 devDepencies 都不会被下载。

总结

对于项目,npm install 会下载 dependenciesdevDependencies 中的依赖(如果加上参数 --production 只会下载 dependencies 中的);而依赖中的依赖,只会下载 dependencies 里的。

最后总结一句话:如果没有这个包项目跑不起来,那么把它安装在 dependencies 中;如果这个包只是在开发时用于打包,测试...等,把它安装在 devDependencies 中。

以上 🚀

@liuyib liuyib added the npm📦 JavaScript 包管理工具 - npm label Feb 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
npm📦 JavaScript 包管理工具 - npm
Projects
None yet
Development

No branches or pull requests

1 participant