Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Node wraps every .js file in a module function, which creates file-level scope. In contrast, all files are part of global scope (window object) for js in browser. To use functions from one module in another, it is necessary to export/import.
- A property of the wrapper function is module.exports. It exists as an empty object if no exports have been defined. Exporting is is as simple as adding functions/vars to the module.exports object with module.exports = function or var. To import, use the requires(<path to export module>) method.
- In the code below, function doesSomething is exported from file1.js and imported in file2.js
- */
- // EXPORT
- // file1.js
- function doesSomething() {
- // block of code
- return something;
- }
- // style 1
- module.exports.doesSomething = doesSomething; // exports entire module.exports object
- // style 2
- module.exports = doesSomething; // exports only the function
- // IMPORT
- // file2.js
- const importedFunc = require('relative-path-to-module'); // if in same dir, (./module). Note file extension absent.
Add Comment
Please, Sign In to add comment