一个文件的代码是:
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
另一个文件的代码是:
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3));
运行时报错:
SyntaxError: import declarations may only appear at top level of a module
import { square, diag } from 'lib';
我只是想支持es6语法而已,所以还没安装webpack。
import语句必须在该文件的最上方,不像require可以随时用。
你为什么不看看用babel转换之后的代码是什么样子的呢……
首先,不知道你的 Babel 是怎么调用的;其次,不知道你的脚本是在 Web 环境还是在 NodeJS 环境运行的。
NodeJs 目前不支持 es2015 的 module,如果你用 Babel 编译,需要使用 transform-es2015-modules-commonjs 插件 来将 es2015 的 module 转换成 nodejs 支持的 commonjs。如果是在网页上,你可以考虑 AMD 之类的 module 格式,也需要用相应的插件来处理。
你的代码报错提示的并不是因为不支持es6,而是因为你import用错了
import { square, diag } from './lib';