Close

JavaScript Modules - Named Imports

[Updated: Nov 30, 2018, Created: Nov 26, 2018]

Instead of importing all exported features via import * as XYZ (last tutorial), ES6 specifications allows to selectively import features.
Following syntaxes are supported:

Importing named features selectively:

import {a, b, c, .....} from "module-name"

Where a, b, c .. are one or more selected variables/functions/classes we want to import.

Importing named features with aliases:

import {a as alias1, b as alias2, c as alias3, .....} from "module-name"

Where a, b, c .. are one or more selected variables/functions/classes we want to import and alias1, alias2, alias3 .. are the respective local names referred to the named imports.

We can also mix the two styles:

import {a as alias1, b, c as alias2, .....} from "module-name"

Examples

js/lib.js

export function showSquare(num) {
    show(num * num);
}

export function showSum(x, y) {
    show(x + y);
}

export function showSquareRoot(x){
   show(Math.sqrt(x));
}

function show(result) {
    console.log(result);
}

js/app.js

import {showSquare, showSquareRoot} from "./lib.js";

showSquare(2);
showSquareRoot(2);

index.html

<html>
<script type="module" src="./js/app.js"></script>
<body>

</body>
</html>

Output

To try examples, run http-server from project root:

$ http-server

On loading the index page in browser, the console shows:

4
1.4142135623730951

Using aliases:

js/app.js

import {showSquare as square, showSquareRoot as sqrt} from "./lib.js";

square(2);
sqrt(2);

Other two files are same. The output is also same as the last example.

Example Project

Dependencies and Technologies Used:

  • techUsed=Node.js v8.11.3
  • Google Chrome Browser Version 70.0.3538.102 (Official Build) (64-bit)
JavaScript Modules - Named Imports Select All Download
  • javascript-named-imports
    • js
      • app.js
    JavaScript Modules - Named Imports with Aliases Select All Download
    • javascript-named-imports-with-aliases
      • js
        • app.js

      See Also