Javascript Module - Import (Es Module)
Table of Contents
About
The import statement for a es module
The ES6 import is:
- a function for dynamic import (performed at runtime time)
- or a statement for static import (performed at build time)
that is used to import:
- or primitives
that have been exported from:
- an external ES module,
- another module such as commonCommonJS and AMD modules.
- etc.
- ES6
import Member from "ModuleName";
- in ES5: require statement (is a commonJs statement)
var Member = require("ModuleName").default;
This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers.
Not to be confound with the import expression in CSS. See CSS - @import rule.
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
Syntax
Static
- Import the default member. It is possible to have a default export
import defaultMember from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
- Import an entire module namespace object where the properties are the module’s exports with the alias 'name'. 'name' is inserted into the current scope.
import * as name from "module-name";
// if the “module-name” module exports a function named foo(), you can write:
name.foo()
- Import a single member of a module. This inserts member into the current scope.
import { member } from "module-name";
import { member as alias } from "module-name";
- Import multiple members of a module.
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
- Import an entire module for side effects only, without importing any bindings.
import "module-name";
Dynamic
Example
Module Location
- Supported:
// Via the http(s) scheme
import {foo} from 'https://example.com/.../bar.js';
// Full Qualified
import {foo} from '/foo/bar.js';
// Relative
import {foo} from './bar.js';
import {foo} from '../bar.js';
- Supported using NODE_PATH in some module loader
import {foo} from 'bar.js';
import {foo} from 'foo/bar.js';
Mozilla Doc
- Module:
// --file.js--
function getJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText)
};
xhr.open('GET', url, true);
xhr.send();
}
export function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
- Import
import { getUsefulContents } from 'myModuleFile.js';
getUsefulContents('http://www.example.com', data => {
doSomethingUseful(data);
});