Reputation: 63415
I don't know if there's a recommended or standard approach, but I saw examples like this:
my-project
package.json
src
index.js
[...]
and like this:
my-project
src
package.json
index.js
[...]
What is the recommend way to do it? Are there any pros/cons to each approach?
Upvotes: 14
Views: 15986
Reputation: 4998
I'd say there are three main things to consider.
1) You generally want to place package.json
in the directory where you'll be running npm commands, like npm install
or any npm scripts defined in the package.json
's "scripts: {..}"
. Also, npm install
pulls all the modules into the node_modules
directory right next to your package.json
:
my-project
node_modules
package.json
src
index.js
[...]
Of course, you could always cd
into the directory first, or use the --prefix
flag, but why make life harder?
2) When you require()
a 3rd-party module in your .js
files, node.js will look for it in a closest node_modules
directory, starting from the current directory and making its way up until it finds one. This article explains it well. You can use this logic to isolate dependencies to different contexts like src/
and test/
, but it usually makes more sense to have a common node_modules
for the whole project you're working on.
3) If you're planning to publish your package, you'll have to place package.json
with necessary metadata to the root directory of the said package. When someone installs your package later, npm will expect to see package.json
in its root directory.
Upvotes: 7
Reputation: 2233
It should be in the root of the project.
my-project
package.json
src
index.js
[...]
If you do npm init
it will put in the root of the project
Upvotes: 4