module.exports
is the object that's actually returned as the result of a require
call.
The exports
variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:
let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
to export (or "expose") the internally scoped functions myFunc1
and myFunc2
.
And in the calling code you would use:
const m = require('./mymodule');
m.myFunc1();
where the last line shows how the result of require
is (usually) just a plain object whose properties may be accessed.
NB: if you overwrite exports
then it will no longer refer to module.exports
. So if you wish to assign a new object (or a function reference) to exports
then you should also assign that new object to module.exports
It's worth noting that the name added to the exports
object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:
let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
followed by:
const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName
There's not much of one in everyday work.
However, according to the documentation for both functions (accessed by putting a ?
before the function name and hitting enter), require
is used inside functions, as it outputs a warning and continues if the package is not found, whereas library
will throw an error.
Best Answer
The difference between
--save
and--save-dev
may not be immediately noticeable if you have tried them both on your own projects. So here are a few examples...Let's say you were building an app that used the moment package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: cannot run without it. In this case you would use
This would create a new value in your package.json
When you are developing, it really helps to use tools such as test suites and may need jasmine-core and karma. In this case you would use
This would also create a new value in your package.json
You do not need the test suite to run the app in its normal state, so it is a
--save-dev
type dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine.Taken directly from NPM docs docs#dependencies
Even in the docs, it asks you to use --save-dev for modules such as test harnesses.
I hope this helps and is clear.