Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

I'm new to ES6 (ECMAScript 6), and I'd like to use its module system in the browser. I read ES6 is supported by Firefox and Chrome, but I'm getting the following error using export

Uncaught SyntaxError: Unexpected token import

I have a test.html file

<html>     <script src="test.js"></script> <body> </body> </html> 

and a test.js file

'use strict';  class Test {      static hello() {         console.log("hello world");     }  }  export Test;     

Why?

like image 915
cdarwin Avatar asked Jan 18 '17 14:01

cdarwin


2 Answers

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

like image 151
vullnetyy Avatar answered Oct 20 '22 04:10

vullnetyy


You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.

Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/

I've basic demo -

//app.js import {sum} from './calc.js'  console.log(sum(2,3)); 
//calc.js let sum = (a,b) => { return a + b; }  export {sum}; 
<html>      <head>         <meta charset="utf-8" />     </head>      <body>         <h1>ES6</h1>         <script src="app.js" type="module"></script>     </body>  </html> 

Hope it helps!

like image 22
Roopesh Reddy Avatar answered Oct 20 '22 04:10

Roopesh Reddy