我有一个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,请参考本文档。只要在你的节点应用程序中设置babel,它就会工作,它为我工作。

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

其他回答

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

只需添加——presets '@babel/preset-env'。

例如,

babel-node --trace-deprecation --presets '@babel/preset-env' ./yourscript.js

Or

在babel.config.js

module.exports = {
  presets: ['@babel/preset-env'],
};

对我来说。我认为问题出在标准节点可执行文件上。节点target.ts

我用nodemon替换了它,令人惊讶的是它竟然工作了!

使用标准可执行文件(runner)的方式:

node target.ts

使用nodemon可执行文件(runner)的方式:

nodemon target.ts

不要忘记用npm install nodemon;P

注意:这对于开发非常有效。但是,对于运行时,你可以使用编译后的js文件执行node !

取出"module": "esnext"并确保" modulerresolve ": "node"在其中,这个特定的组合为我做了

如果你正在使用ES6 JavaScript导入:

安装cross-env 在包中。将“test”:“jest”改为“test”:“cross-env NODE_OPTIONS=——experimental-vm-modules jest” 更多的包装。Json,添加这些:

    ...,
    "jest": {
        "transform": {}
    },
    "type": "module"

解释:

Cross-env允许在不更改NPM命令的情况下更改环境变量。接下来,在文件包中。你改变你的npm命令来启用实验性的ES6对Jest的支持,并配置Jest来做到这一点。