我有一个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在我的计算机上执行一些本地任务。

让我们假设我的旧脚本是test.js。在里面,如果我想用的话

import something from "./mylocalECMAmodule";

它会抛出一个这样的错误:

(node:16012) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module
...

这不是模块错误,而是Node.js错误。禁止加载“模块”之外的任何东西。

要解决这个问题,只需将旧脚本test.js重命名为test.mjs。

这是所有。

其他回答

如果您正在为Node.js版本12运行nodemon,请使用此命令。

Server.js是里面的“主”包。Json文件,将其替换为包内的相关文件。json文件:

nodemon --experimental-modules server.js

当您运行该命令时也会出现此错误

node filename.ts

而不是

node filename.js

简单地说,使用node命令,我们必须运行JavaScript文件(filename.js),而不是TypeScript文件,除非我们使用像ts-node这样的包。

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

根据官方文件:

import语句只允许在ES模块中使用。要了解CommonJS中的类似功能,请参见import()。

为了让Node.js把你的文件当作ES模块,你需要(启用):

在package.json中添加"type": "module" 在Node.js调用中添加"——experimental-modules"标志

我也有同样的问题,下面已经修复了它(使用Node.js 12.13.1):

将.js文件扩展名更改为.mjs 在运行应用程序时添加——experimental-modules标志。 可选:在package.json中添加"type": "module"

更多信息:https://nodejs.org/api/esm.html