Javascript - Import

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard > Javascript ES - Module Script

1 - About

The import statement implementation in ECMAScript

The ES6 import statement is used to import:

that have been exported from:

  • ES6
import Member from "ModuleName";
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');
Advertising

3 - Syntax

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";

4 - Example

4.1 - 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';
Advertising

4.2 - Mozilla Doc

  • Module:
myModuleFile.js
// --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);
});

5 - Documentation / Reference

web/javascript/es/module/import.txt · Last modified: 2019/03/20 20:55 by gerardnico