Search code examples
javascriptgoogle-chromeecmascript-6transpiler

import / export in ES6 Transpilers


This is not a duplicate of below questions which is dealing with browser specific questions. I'm expecting an answer whether import / export will work in Client side or not.

  1. ECMA 6 Not working although experimental js is enabled
  2. how export variable in ES6 in Chrome/Firefox?

//lib.js

export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
  
//main.js
  
"use strict";

import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Import Check</title>
</head>
<body>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

Error that I'm getting in Chrome:
enter image description here

Tested Browser: Google Chrome Version 47.0.2526.106

  1. Is that possible to make the code working in any browser or not ?
  2. Lets say, we have chosen one transpiler (BabelJS) and code got transpiled. Will the import / export file code snippet will work in the Client side or Server side (In node Server as require method)?

Solution

  • MDN says

    Note: This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.

    For example after using babel on your code snippet you will get something like this:

    //lib.js
    
    "use strict";
    
    Object.defineProperty(exports, "__esModule", {
        value: true
    });
    exports.square = square;
    exports.diag = diag;
    var sqrt = Math.sqrt;
    exports.sqrt = sqrt;
    
    function square(x) {
        return x * x;
    }
    
    function diag(x, y) {
        return sqrt(square(x) + square(y));
    }
    //------ main.js ------
    'use strict';
    
    var _lib = require('lib');
    
    console.log((0, _lib.square)(11)); // 121
    console.log((0, _lib.diag)(4, 3)); // 5

    This code is enough to use in NodeJs. But to use in browser you need something like require.js or browserify. In this plunker I used require1k