我有一个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",

当前回答

只需将其更改为:

const uuidv1 = require('uuid');

它会工作得很好。

其他回答

我最近遇到了这个问题。对我有效的修复是将此添加到插件部分的babel.config.json文件中:

["@babel/plugin-transform-modules-commonjs", {
    "allowTopLevelThis": true,
    "loose": true,
    "lazy": true
  }],

我有一些导入模块与//和错误“不能使用导入模块外”。

我的解决方案是在运行nodemon时包含babel-node路径,如下所示:

nodemon node_modules/.bin/babel-node index.js

你可以加入你的套餐。Json脚本如下:

debug: nodemon node_modules/.bin/babel-node index.js

注意:我的入口文件是index.js。将其替换为您的入口文件(许多有app.js/server.js)。

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

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

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

如果您正在使用node,请参考本文档。只要在你的节点应用程序中设置babel,它就会工作,它为我工作。

npm install --save-dev @babel/cli @babel/core @babel/preset-env

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

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

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