- The JavaScript language didn’t have a native way of organizing code before the ES2015 standard.
- Node.js filled this gap with the CommonJS module format.
- The module system allows you to organize your code, hide information and only expose the public interface of a component using
module.exports
. Every time you use therequire
call, you are loading another module. - do not use
exports = xxx
directly, usemodule.exports = xxx
insteadly.
Module is wrapped by Node.js this way
(function (exports, require, module, __filename, __dirname) {
function add (a, b) {
return a + b
}
module.exports = add
})
This is why you can access the global-like variables like require
and module
. It also ensures that your variables are scoped to your module rather than the global object.
How does require
works
- The module loading mechanism in Node.js is caching the modules on the first
require
call. - The module dealing with module loading in the Node core is called
module.js
, and can be found in lib/module.js in the Node.js repository. - Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions?
What’s in your node_modules?
- npm v2: npm 2 installs all dependencies in a nested way, where your primary package dependencies are in their
node_modules
folder. - npm v3: npm3 attempts to flatten these secondary dependencies and install them in the root
node_modules
folder. This means that you can’t tell by looking at yournode_modules
which packages are your explicit or implicit dependencies.
ES2015
- As we saw above, the CommonJS module system uses a runtime evaluation of the modules, wrapping them into a function before the execution.
- The ES2015 modules don’t need to be wrapped since the
import
/export
bindings are created before evaluating the module. This incompatibility is the reason that currently there are no JavaScript runtime supporting the ES modules.
The structure
- JS world
- ECMAScript standards
- ES5
- ES6/ES2015
- TypeScript
- ECMAScript standards
- Other information
- ES5 is what most of us have used for years. Functional programming at its best, or worst, depending on how you view it. I personally love programming with ES5. All modern browsers support it.
ECMAScript 2015
is an ECMAScript standard that was ratified in June 2015.
How to enable ES2015 in nodejs
- How do we run ES2015 in browsers that do not yet support ES2015? We can use ES2015 and transpile to ES5 using a tool like
Babel
.
Other module system
References
- How the module system, CommonJS & require works | @RisingStack
- javascript - What is the purpose of Node.js module.exports and how do you use it? - Stack Overflow
- Learn the basics of the JavaScript module system and build your own library
- Node.js, TC-39, and Modules – Hacker Noon
- export - Web technology for developers | MDN
- Other