ES2015 module import and export syntax error

2020-06-01 08:37发布

问题:

On using import export in ES6, I'm getting below error:

SyntaxError: export declarations may only appear at top level

I surfed to find how to fix this, but im unable to. Can anybody explain about this. Im new to ES6, especially to import and export. (I was using StealJS completely for this kind of stuffs) Thanks!

js files are:

app.js

import { cube, cubeRoot } from 'functions';

console.log(cube(4));
console.log(cubeRoot(125));

functions.js

// functions.js

function cube(a) {
    return a * a * a;
}

function cubeRoot(a) {
    return Math.cbrt(a);
}

export { cube, cubeRoot}

回答1:

Update summer 2017:

See http://caniuse.com/#search=modules, new support, maybe need to change settings.

Now that things are less vague. To make a module work you have to tell the browser that it is a module (the other being script). The first way is implicit, an imported module is always a module. The second way is with type module<script src="anymodule.js" type="module"></script>

Make sure import and export are only at top level, not inside a block, not inside an if statement, not inside a loop, etc.

Also make sure to provide the full path (including .js), it should start with ./ or ../. Assumming the files are in the same folder it would be import { cube, cubeRoot } from './functions.js';

eval on a module string will not work.

Outdated answer below:

The ES2015 module import and export syntax is not supported by any browser at the time I write this answer (04/2016). The error message is miss leading because it implies that the syntax is supported, but it is not supported at all. See the first note here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

The reason is because the specification for module loaders is still a work in progress. See https://whatwg.github.io/loader/#status

They are tools however to polyfill or to transpile this syntax automatically like babel .