Babel ES6 导入错误,SyntaxError:意外的令牌导入

5

我正在尝试设置一个基本的模块化程序,但是在导入模块时遇到了问题。当我尝试导入自定义模块时,我得到以下错误:

(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep';
                                                          ^^^^^^
SyntaxError: Unexpected token import

引起问题的代码:
testcase.js
import testStep from 'testStep';

testStep.hello();

testStep.js

var testStep = {
  hello: hello,
};

var hello = () => {
  console.log('hello world');
};

export default {testStep};

package.json

{
  "name": "rebuild-poc",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-polyfill": "^6.23.0",
    "babel-preset-env": "^1.6.0"
  },
  "dependencies": {}
}

.babelrc

{
  "presets": [
    "env"
  ]
}

我已经尝试了几种其他的解决方法,比如将testStep设置为类,以及使用require('./testStep.js'),但这些方法似乎都没有起作用。

我是否在babel或我的某个文件中设置了错误?

***编辑:我正在使用node testCase.js运行testCase.js


看起来testStep里有一个多余的括号或逗号。 - Matthew
1
import不能在函数内部。 - Jaromanda X
@Matthew 在 ES6 中允许使用尾随逗号,但我尝试将其移除后问题仍未得到解决。 - Graeham Broda
@JaromandaX,您能再详细解释一下吗?据我所知,这个导入不是在函数内部,而只是在脚本中,但也许我有误解。 - Graeham Broda
1
它位于IIFE内部(根据错误消息)……“导入声明仅允许在模块范围的顶层进行”……不过,我现在更仔细地查看问题中的代码后,可能会误解您正在获取的错误输出。 - Jaromanda X
你检查过这个了吗?看起来你需要将预设设置为es2015 - Matthew
3个回答

5
请安装babel-cli并使用以下方式调用文件:./node_modules/.bin/babel-node testcase.js 它会失败。现在我们需要修复你的代码。
testStep.js应该像这样:
var hello = () => {
  console.log('hello world');
};

var testStep = {
  hello: hello,
};

export default testStep;

那么,它将起作用。;)

https://babeljs.io/上的第一个介绍是,您需要安装babel-clibabel-preset-env。;)

您还可以像这样编写testStep.js:

var testStep = {
  hello: hello,
};

function hello () {
  console.log('hello world');
};

export default testStep;

这需要记住提升变量的概念,就像Jacob在他的第一点所说的那样。

3

2
Babel 建议使用另一个包 babel-preset-env - Anthony Kong

0
  1. 你需要使用 function 定义 hello,并使用 var,这样你就不会有 function hoisting 的问题,因此在声明 testStep 时,hello 是未定义的。

  2. 如果你想使用 ES 模块,可以使用 babel-registerbabel-node。 在你的代码中,Node 无法处理 ES 模块。

Babel-register

使用 babel-register,当导入模块时,所有模块都将由 Babel 处理。

首先,运行命令:yarn add babel-register babel-cli --devnpm install babel-register babel-cli --dev, 然后创建一个入口文件:

// entry.js
require('babel-register')
require('testcase')

在你的测试用例中,现在可以使用 ES 模块。
编辑你的 package.json:
"scripts": {
    "test": "node entry.js"
},

您可以在终端中运行yarn testnpm run test

您不需要babel-polyfill,它是为浏览器而设计的,而不是为Node.js。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接