11

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?

opensas
  • 60,462
  • 79
  • 252
  • 386
  • 1
    Id put it in root, this way as you enter the project you dont have to first enter src to install, second, if you have files outside, like tests then you don't need another package.json/node_modules per folder. – Lawrence Cherone Sep 09 '19 at 04:16

2 Answers2

5

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.

shkaper
  • 4,689
  • 1
  • 22
  • 35
4

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

Pranoy Sarkar
  • 1,965
  • 14
  • 31