Modules are very useful when we want to make more reusable code, for example when you want some function or variable to be used outside the current module, that's when you need to export a module, similarly you also can import a module in JavaScript, in this tutorial you will learn Javascript ES6 modules.
ES6 modules are basically JavaScript File, so when you write any function in any JavaScript file those are not accessible outside the file by default, unless you export them!
To export any variable or function outside the module you need to use export
keyword,
let's look at the example below.
Here I have created a simple JavaScript file with “wc.js ”, and written the following codes
export var welcomeMessage = 'Welcome to WTR'; export function greetingMessage() { return welcomeMessage; }
Now above function and variable will be accessible in a new file.
Now you see how to import the above functionality in a new module (JavaScript file)
Notice in following code, We use require
to import a module, and when we write require('./module-name')
, that indicates that’s a new local module.
let _wc = require('./wc'); _wc.greetingMessage();
Above example was of importing the entire module, means if there are 10 functions were written with export, all function will be available in our new module.
You also can import one particular binding instead of entire module as an object.
In earlier example we have seen how to import module using require
keyword, here we use import
keyword to import a module.
import * as s from './sample.js'; //will import the entire module import {Notify} from './sample.js'; // will import only specified function of that module
Now you may think why using two different approaches to import a module, require
and import
,
at the end both does the same job but differently
Actually, require
is used in Node.js and import
for ES6, but there is no JavaScript engine for ES6,
you may use Babel or Node or may be something similar.
Now Babel converts import
declaration to CommonJS, even Node runtime also use CommonJS.
So to simplify the difference, as per CommonJs syntax, it uses “require” and as per ES6 it uses “Import”.
You may read further to understand technical differences between CommonJS and ES6 modules.