Import/Export Vs Require/Module.exports

Import/Export

1) Named exports (several per module)

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
// module "my-module.js"
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
// module "my-module.js"
export default function cube(x) {
return x * x * x;
}
import cube from './my-module.js';
console.log(cube(3)); // 27

require and module.exports

Best blog to read about in detail:
https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8

require.resolve

If you want to only resolve the module and not execute it, you can use the require.resolve function. This behaves exactly the same as the main require function, but does not load the file. It will still throw an error if the file does not exist and it will return the full path to the file when found.

exports, module.exports, and synchronous loading of modules

A module object has ‘exports’ property.We can add any attribute to this special exports object. For example, let’s export an id attribute for index.js and lib/util.js:

// Add the following line at the top of lib/util.js
exports.id = 'lib/util';
// Add the following line at the top of index.js
exports.id = 'index';
exports.id = 42; // This is ok.exports = { id: 42 }; // This will not work.module.exports = { id: 42 }; // This is ok.

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store