我有一个ApolloServer项目,它给我带来了麻烦,所以我想我可能会更新它,但在使用最新的Babel时遇到了问题。我的index.js是:

require('dotenv').config()
import {startServer} from './server'
startServer()

当我运行它时,我得到了错误

SyntaxError: Cannot use import statement outside a module

首先,我试图说服TPTB*这是一个模块(没有成功)。所以我把“import”改成了“require”,这就成功了。

但现在我在其他文件中有大约24个“导入”给我同样的错误。

*我敢肯定我问题的根源是我甚至不知道抱怨的是什么。我有点假设它是巴别塔7(因为我来自巴别塔6,我不得不改变预设),但我不是100%确定。

我发现的大多数解决方案似乎并不适用于直节点。比如这个:

ES6模块导入给出“未捕获SyntaxError:意外标识符”

说它是通过添加“type=module”来解决的,但这通常会在HTML中,其中我没有。我也尝试使用我的项目的旧预设:

"presets": ["es2015", "stage-2"],
"plugins": []

但这又给了我另一个错误:“错误:插件/预设文件不允许导出对象,只能导出函数。”

以下是我开始时的依赖关系:

"dependencies": {
"@babel/polyfill": "^7.6.0",
"apollo-link-error": "^1.1.12",
"apollo-link-http": "^1.5.16",
"apollo-server": "^2.9.6",
"babel-preset-es2015": "^6.24.1",

当前回答

验证您已经安装了Node.js的最新版本(或至少13.2.0+)。然后按照文档中的描述,执行以下操作之一:

选项1

在最近的父包中。Json文件,添加顶级的“type”字段,值为“module”。这将确保所有.js和.mjs文件都被解释为ES模块。您可以使用.cjs扩展名将单个文件解释为CommonJS。

// package.json
{
  "type": "module"
}

选项2

显式地以.mjs扩展名命名文件。所有其他文件,如.js将被解释为CommonJS,如果package.json中没有定义type,则CommonJS是默认值。

其他回答

要使用导入,请执行以下操作之一。

将.js文件重命名为.mjs 在包中。Json文件,添加{type:module}

对于那些和我一样在阅读答案时感到困惑的人,在你的包裹里。Json文件,添加 “类型”:“模块” 在上层如下图所示:

{
  "name": "my-app",
  "version": "0.0.0",
  "type": "module",
  "scripts": { ...
  },
  ...
}

为了让你的导入工作并避免其他问题,比如模块不能在Node.js中工作,请注意:

在ES6模块中,你还不能导入目录。你的导入应该是这样的:

import fs from './../node_modules/file-system/file-system.js'

I had the same problem when I started to use Babel... But later, I had a solution... I haven't had the problem any more so far... Currently, Node.js v12.14.1, "@babel/node": "^7.8.4", I use babel-node and nodemon to execute (Node.js is fine as well..) package.json: "start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js"!! Note: server.js is my entry file, and you can use yours. launch.json. When you debug, you also need to configure your launch.json file "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node"!! Note: plus runtimeExecutable into the configuration. Of course, with babel-node, you also normally need and edit another file, such as the babel.config.js/.babelrc file

验证您已经安装了Node.js的最新版本(或至少13.2.0+)。然后按照文档中的描述,执行以下操作之一:

选项1

在最近的父包中。Json文件,添加顶级的“type”字段,值为“module”。这将确保所有.js和.mjs文件都被解释为ES模块。您可以使用.cjs扩展名将单个文件解释为CommonJS。

// package.json
{
  "type": "module"
}

选项2

显式地以.mjs扩展名命名文件。所有其他文件,如.js将被解释为CommonJS,如果package.json中没有定义type,则CommonJS是默认值。