Search code examples
javascriptgoogle-chromeecmascript-6includebabeljs

JS: enabling export/import on client side (ES6 or using babel)?


I want to export/import local files within an app directory:

My index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<script type="text/babel" src="main.js"></script>
</body>
</html>

actions.js:

export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'

main.js (loaded from index.html):

import {ADD_TODO, TOGGLE_TODO, SET_VISIBILITY_FILTER} from 'actions'

Now if I use javascript without babel, I will get:

Uncaught SyntaxError: Unexpected token import

I use Chrome browser version 60. Shouldn't this version already support ES6? And by supporting, I should be able to use export/import?

I also tried with babel (using standalone babel loaded from index.html).

Then I get this error:

Uncaught ReferenceError: require is not defined
    at <anonymous>:4:16
    at n (https://unpkg.com/[email protected]/babel.min.js:12:27049)
    at r (https://unpkg.com/[email protected]/babel.min.js:12:27558)
    at e.src.i.(anonymous function).error (https://unpkg.com/[email protected]/babel.min.js:12:27873)
    at XMLHttpRequest.i.onreadystatechange (https://unpkg.com/[email protected]/babel.min.js:12:27316)

I understand that require does not exist on client side, but isn't that export/import (not NodeJS export) syntax for ES6?..

Do I need to resort to things like webpack for this to work?

According to this answer: Trying ES6 imports with Chrome but it doesn't seem to work you need to enable Experimental Web Platform flag in Chrome and use <script type="module" src="main.js"></script>. But using it, stops loading anything. It seems browser just ignores such type. And even if this approach would work, then I guess I would not be able to use babel then, because it would use different type?

P.S. According to this: http://2ality.com/2014/09/es6-modules-final.html#named-exports-several-per-module it should work..


Solution

  • Chrome has achieved most of the es6 new features, except import / export has not yet achieved,for more detail:https://ruanyf.github.io/es-checker/

    If you don't want use webpack to compile files,try:

    $ npm install --global babel-cli
    

    and then:

    babel example.js -o compiled.js
    

    finally,you will get the compiled files,which will support browsers。

    plus,the key word require/exports/module.exports is a CommonJS specification,supported by Node.js.The file https://unpkg.com/[email protected]/babel.min.jsused the CommonJS specification, so it will be reported errors on the browser side