语法错误:不能在模块外使用导入语句 [英] SyntaxError: Cannot use import statement outside a module

查看:53
本文介绍了语法错误:不能在模块外使用导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got an ApolloServer project that's giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My "index.js" is:

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

当我运行它时,我收到错误

And when I run it I get the error

SyntaxError: Cannot use import statement outside a module

首先,我试图说服 TPTB* 这是一个模块(但没有成功).所以我改变了import"到要求"这奏效了.

First I tried doing things to convince TPTB* that this was a module (with no success). So I changed the "import" to a "require" and this worked.

但现在我有大约两打进口";在其他文件中给我同样的错误.

But now I have about two dozen "imports" in other files giving me the same error.

*我确信我的问题的根源在于我什至不确定是什么原因导致了这个问题.我有点假设它是 Babel 7(因为我来自 Babel 6,我不得不更改预设)但我不是 100% 确定.

*I'm sure the root of my problem is that I'm not even sure what's complaining about the issue. I sort of assumed it was Babel 7 (since I'm coming from Babel 6 and I had to change the presets) but I'm not 100% sure.

我为解决方案找到的大部分内容似乎不适用于直接 Node.js.像这里的这个:

Most of what I've found for solutions don't seem to apply to straight Node. Like this one here:

ES6 模块导入给出 "未捕获的语法错误:意外的标识符

说它是通过添加type=module"解决的但这通常会出现在 HTML 中,而我没有.我也试过使用我项目的旧预设:

Says it was resolved by adding "type=module" but this would typically go in the HTML, of which I have none. I've also tried using my project's old presets:

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

但这让我又犯了一个错误:错误:插件/预设文件不允许导出对象,只能导出函数."

But that gets me another error: "Error: Plugin/Preset files are not allowed to export objects, only functions."

以下是我开始使用的依赖项:

Here are the dependencies I started with:

"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+).然后执行以下操作之一,如文档中所述:

Verify that you have the latest version of Node.js installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:

选项 1

在最近的父package.json文件中,添加值为module"type"字段>.这将确保所有 .js.mjs 文件都被解释为 ES 模块.您可以使用 .cjs 扩展名将单个文件解释为 CommonJS.

In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.

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

选项 2

使用 .mjs 扩展名显式命名文件.所有其他文件,例如 .js 将被解释为 CommonJS,这是如果 package.json 中未定义 type 的默认设置.

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

这篇关于语法错误:不能在模块外使用导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆