ES2015模块导入和导出语法错误 [英] ES2015 module import and export syntax error

查看:187
本文介绍了ES2015模块导入和导出语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ES6中使用导入导出时,我收到以下错误:

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


语法错误:导出声明​​可能只出现在顶层

SyntaxError: export declarations may only appear at top level

我浏览了解如何修复此问题,但我无法解决。任何人都可以解释一下。我是ES6的新手,特别是进口和出口。 (我完全使用StealJS来处理这类东西)
谢谢!

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文件是:

app.js

import { cube, cubeRoot } from 'functions';

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

functions.js

functions.js

// functions.js

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

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

export { cube, cubeRoot}


推荐答案

2017年夏季更新:

Update summer 2017:

参见 http://caniuse.com/#search=modules ,新支持,可能需要更改设置。

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

现在事情不那么模糊了。要使模块工作,您必须告诉浏览器它是一个模块(另一个是脚本)。第一种方式是隐式的,导入的模块总是一个模块。第二种方式是类型模块< script src =anymodule.jstype =module>< / script>

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>

确保导入和导出仅在顶层,不在块内,不在if语句内,不在循环内等。

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

还要确保提供完整路径(包括.js),它应该以 ./ 或<开头code> ../ 。假设文件位于同一个文件夹中,它是从'./functions.js'导入{cube,cubeRoot};

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 将无效。

以下过时答案:

在我写这个答案时(04/2016),任何浏览器都不支持ES2015模块导入和导出语法。错误消息未命中,因为它意味着支持语法,但根本不支持。请参阅 https://developer.mozilla。 org / zh-CN / docs / Web / JavaScript / Reference / Statements / import

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

原因是因为模块加载器的规范仍然是一个工作原理进展。请参阅 https://whatwg.github.io/loader/#status

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

然而,它们是polyfill或者像babel一样自动转换这种语法的工具。

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

这篇关于ES2015模块导入和导出语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆