Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node: should package.json be in the src folder or in the parent folder?

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?

like image 304
opensas Avatar asked Sep 09 '19 04:09

opensas


People also ask

Where should package json be located?

The package. json file is normally located at the root directory of a Node. js project. The name field should explain itself: this is the name of your project.

What is src folder in node JS?

The /src folder contains all the sources, i.e. the code which is required to be manipulated before it can be used.

Where do I put NPM packages?

NPM installs global packages into /<User>/local/lib/node_modules folder. Apply -g in the install command to install package globally.

How does node use package json?

The package. json file is the heart of any Node project. It records important metadata about a project which is required before publishing to NPM, and also defines functional attributes of a project that npm uses to install dependencies, run scripts, and identify the entry point to our package.


2 Answers

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

like image 54
Pranoy Sarkar Avatar answered Oct 06 '22 06:10

Pranoy Sarkar


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.

like image 29
shkaper Avatar answered Oct 06 '22 07:10

shkaper