What is the difference between a package and a module in JavaScript?
In short, the key difference is that a package includes a package.json file, but a module doesn't have to have it.
In common practice, a package is regarded as a collection of modules, and a module as a single file.
> Official npm definition (docs.npmjs.com):
- Package: a file or directory that is described by a package.json file. A package must contain a package.json file in order to be published to the npm registry.
A package is any of the following:
- A folder containing a program described by a package.json file.
- A gzipped tarball containing (a).
- A URL that resolves to (b).
- A <name>@<version>
that is published on the registry with (c).
- A <name>@<tag>
that points to (d).
- A <name>
that has a latest tag satisfying (e).
- A git url that, when cloned, results in (a).
- Module: any file or directory in the node_modules directory that can be loaded by the Node.js
require()
function.
To be loaded by the Node.js require()
function, a module must be one of the following:
- A folder with a package.json file containing a "main" field.
- A folder with an index.js file in it.
- A JavaScript file.
| Note: Since modules are not required to have a package.json file, not all modules are packages. Only modules that have a package.json file are also packages.