How to export and import local modules in Javascript

Posted on October 5, 2019

Export and import local modules in Javascript

A lot of examples teach you how to import modules in html. But how do you import own-coded modules in JS file? Here is a simple example showing you how to do. More info refer to JS local modules. Main module test.js imports functions from demo_module.js, which is in the same folder as test.js

var mymodule = require('./demo_module.js');
console.log(mymodule.square(11));
console.log(mymodule.diag(4, 3));

In demo_module.js, export your modules

var sqrt = Math.sqrt;
function square(x) {
    return x*x;
}
function diag(x, y) {
    let v = Math.sqrt(square(x) + square(y));
    return v;
};
module.exports.diag = diag;
module.exports.square = square;