ES6 module support for JerryScript

The module system allows users to write import and export statements in scripts. Therefore the logic of the application could be separated in custom modules. The standard’s relevant part can be found here.

General

If the main script contains import statements, then Jerry opens and runs the appropriate scripts before the main script (as the standard says). The script’s and the module’s extension is .js, custom extensions are unnecessary.

main.js

import { secret_number } from "./module.js"

print (secret_number);

module.js

var secret_number = 42;

export secret_number;

Supported features

  • import variable or function
    • add alias name to the imported variable (function)
  • export variable or function
    • add alias name to the exported variable (function)

Example

import {
  engine,
  version as v
} from "./module.js"

import { getFeatureDetails } from "./module_2.js"

var version = "v3.1415";

print("> main.js");

print(">> Engine: " + engine);
print(">> Version: " + v);

print (">> " + getFeatureDetails());
print (">> Script version: " + version);
// module.js
var _engine = "JerryScript";
export _engine as engine;

export var version = "1.0 (e92ae0fb)";
// module_2.js
var featureName = "EcmaScript 2015 modules";
var year = 2018;

export function getFeatureDetails() {
  return "Feature name: " + featureName + " | developed in " + year;
}

Unsupported features

  • snapshot
  • errors from the imported scripts
  • redirection ( export { a, b } from 'module.js' )
  • default import and export
    • import b from 'module.js'
    • export default b,
  • whole module import statements
    • import * from 'module.js
    • import { * as module } from 'module.js
  • object freezing ( Object.freeze (this) )

Redirection

An export statement can import variables from a custom module and export it directly from the current script. This statement is called redirection. In this case the export { b } from 'module2.js' works as the b was imported before then exported as a local variable.

import { a, b } from 'module.js'

print (a + b);
// module.js
export var a = 2;
export { b } from 'module2.js'
// module2.js
export var b = 40;

Default imports and exports

TODO: This part is going to be written in the next part of the patch.

Import the whole module

The whole module can be imported. In this case the m object would contain the exported parts of the module. If the import is not aliased, the global object would contain the exports.

import { * as m } from "./module.js"

print (m.secret_number);
print (m.getPrettifiedNumber());
print (m.api.version);
// module.js
var secret_number = 42;
export secret_number;

export function getPrettifiedNumber() {
  return "*** " + secret_number + " ***";
}

export { ble as api } from "./ble.js";