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?
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.
The /src folder contains all the sources, i.e. the code which is required to be manipulated before it can be used.
NPM installs global packages into /<User>/local/lib/node_modules folder. Apply -g in the install command to install package globally.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With