一个文件的代码是:
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。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你为什么不看看用babel转换之后的代码是什么样子的呢……
首先,不知道你的 Babel 是怎么调用的;其次,不知道你的脚本是在 Web 环境还是在 NodeJS 环境运行的。
NodeJs 目前不支持 es2015 的 module,如果你用 Babel 编译,需要使用 transform-es2015-modules-commonjs 插件 来将 es2015 的 module 转换成 nodejs 支持的 commonjs。如果是在网页上,你可以考虑 AMD 之类的 module 格式,也需要用相应的插件来处理。
你的代码报错提示的并不是因为不支持es6,而是因为你import用错了
import语句必须在该文件的最上方,不像require可以随时用。
我也在这里遇到了一个坑,后来发现添加一个文件就好了,文件名为:.babelrc,
内容如下:
{
}
然后在通过babel-node 你的文件.js
就能运行了!!!
这个是我写的一篇博客具体记录了这个问题:
http://www.jianshu.com/p/4e35...