How to use the 'main' parameter in package.json?
From the npm documentation:
The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.
This should be a module ID relative to the root of your package folder.
For most modules, it makes the most sense to have a main script and often not much else.
To put it short:
- You only need a
main
parameter in yourpackage.json
if the entry point to your package differs fromindex.js
in its root folder. For example, people often put the entry point tolib/index.js
orlib/<packagename>.js
, in this case the corresponding script must be described asmain
inpackage.json
. - You can't have two scripts as
main
, simply because the entry pointrequire('yourpackagename')
must be defined unambiguously.
To answer your first question, the way you load a module is depending on the module entry point and the main parameter of the package.json.
Let's say you have the following file structure:
my-npm-module
|-- lib
| |-- module.js
|-- package.json
Without main parameter in the package.json, you have to load the module by giving the module entry point: require('my-npm-module/lib/module.js')
.
If you set the package.json main parameter as follows "main": "lib/module.js"
, you will be able to load the module this way: require('my-npm-module')
.