Javascript 语法错误:不能在模块外使用导入语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/58384179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:20:42  来源:igfitidea点击:

SyntaxError: Cannot use import statement outside a module

javascriptnode.jsbabeljsapollo-server

提问by user3810626

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:

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

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". 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.

当我运行它时,我收到错误“语法错误:无法在模块外使用导入语句”。首先,我试图说服 TPTB* 这是一个模块(但没有成功)。因此,我将“导入”更改为“要求”,这奏效了。

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

但是现在我在其他文件中有大约两打“导入”给了我同样的错误。

*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.

*我确定我的问题的根源是我什至不确定是什么在抱怨这个问题。我有点假设它是 Babel 7(因为我来自 Babel 6,我不得不更改预设)但我不是 100% 确定。

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

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

ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"

ES6 模块导入给出“Uncaught SyntaxError: Unexpected identifier”

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:

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

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

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

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

UPDATE: 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",

回答by jabacchetta

2020 Update (Node 13.2.0+)

2020 更新(节点 13.2.0+)

Verify that you have the latest version of Node installed. The --experimental-modulesflag is no longer necessary. Simply do one of the following:

验证您是否安装了最新版本的 Node。--experimental-modules不再需要该标志。只需执行以下操作之一

  • Add "type": "module"to the nearest parent package.json. With this, all .jsand .mjsfiles are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjsextension.
  • 添加"type": "module"到最近的 parent package.json。这样,所有.js.mjs文件都被解释为 ES 模块。您可以使用.cjs扩展名将单个文件解释为 CommonJS 。

OR

或者

  • Explicitly name files with the .mjsextension. All other files, such as .jswill be interpreted as CommonJS, which is the default if typeis not defined in package.json.
  • 使用.mjs扩展名显式命名文件。所有其他文件,例如.js将被解释为 CommonJS,如果type未在package.json.

回答by shmekor

According to the official doc (https://nodejs.org/api/esm.html#esm_code_import_code_statements):

根据官方文档(https://nodejs.org/api/esm.html#esm_code_import_code_statements):

import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().

import 语句只允许在 ES 模块中使用。对于 CommonJS 中的类似功能,请参阅 import()。

To make Node treat your file as a ES module you need to (https://nodejs.org/api/esm.html#esm_enabling):

要使 Node 将您的文件视为 ES 模块,您需要(https://nodejs.org/api/esm.html#esm_enabling):

  • add "type": "module" to package.json
  • add "--experimental-modules" flag to the node call
  • 将 "type": "module" 添加到 package.json
  • 在节点调用中添加“--experimental-modules”标志

回答by iseenoob

I had the same issue and the following has fixed it (using node 12.13.1):

我遇到了同样的问题,以下已修复它(使用节点 12.13.1):

  • Change .js files extension to .mjs
  • Add --experimental-modules flag upon running your app.
  • Optional: add "type": "module" in your package.json
  • 将 .js 文件扩展名更改为 .mjs
  • 在运行您的应用程序时添加 --experimental-modules 标志。
  • 可选:在 package.json 中添加 "type": "module"

more info: https://nodejs.org/api/esm.html

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

回答by us_david

I ran into the same issue and it's even worse: I needed both "import" and "require"

我遇到了同样的问题,甚至更糟:我需要“导入”和“需要”

1) Some newer ES6 modules works only with import.
2) Some CommonJS works with require.

1) 一些较新的 ES6 模块仅适用于导入。
2) 一些 CommonJS 与 require 一起工作。

Here is what worked for me:
1) Turn your js file into .mjs as suggested in other answers
2) "require" is not defined with ES6 module, so you can define it this way:

以下是对我
有用的方法:1)按照其他答案中的建议将您的 js 文件转换为 .mjs
2)ES6 模块未定义“require”,因此您可以这样定义它:

import { createRequire } from 'module'
 const require = createRequire(import.meta.url);

now 'require' can be used in the usual way.

现在可以以通常的方式使用'require'。

3) Use import for ES6 modules and require for commonJS.

3) ES6 模块使用 import,commonJS 使用 require。

Some useful links: node.js's own documentation. difference between import and require. Microsoft has some nice documentation about import

一些有用的链接: node.js's own documentationimport 和 require 之间的区别微软有一些关于导入的很好的文档

Hope this helps

希望这可以帮助

David

大卫

回答by MrLetmein

  1. I had the same problem when I started to used babel... But later, I had a solution... I haven't had the problem anymore so far... Currently, Node v12.14.1, "@babel/node": "^7.8.4", I use babel-node and nodemon to execute (node is fine as well..)
  2. package.json:"start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js" !!note: server.js is my entry file, you can use yours.
  3. launch.jsonWhen you debug, you also need to config your launch.json file "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node" !!note: plus runtimeExecutable into the configuration.
  4. Of course, with babel-node, you also normally need and edit another file, such as babel.config.js/.babelrc file
  1. 刚开始用 babel 的时候也遇到了同样的问题……不过后来有了解决方案……到现在也没遇到过这个问题……目前是 Node v12.14.1, "@babel/node" : "^7.8.4", 我使用 babel-node 和 nodemon 来执行(节点也很好..)
  2. package.json:"start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js" !!注意:server.js 是我的入口文件,你可以使用你的。
  3. launch.json调试的时候还需要配置你的launch.json文件 "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node" !!注意:在配置中加上runtimeExecutable。
  4. 当然,使用 babel-node,你通常还需要编辑另一个文件,比如 babel.config.js/.babelrc 文件

回答by halfer

I had this problem in a fledgling Express API project.

我在一个刚刚起步的 Express API 项目中遇到了这个问题。

The offending server code in src/server/server.js:

中的违规服务器代码src/server/server.js

import express from 'express';
import {initialDonationItems, initialExpenditureItems} from "./DemoData";

const server = express();

server.get('/api/expenditures', (req, res) => {
  res.type('json');
  res.send(initialExpenditureItems);
});

server.get('/api/donations', (req, res) => {
  res.type('json');
  res.send(initialDonationItems);
});

server.listen(4242, () => console.log('Server is running...'));

Here were my dependencies:

这是我的依赖项:

{
  "name": "contributor-api",
  "version": "0.0.1",
  "description": "A Node backend to provide storage services",
  "scripts": {
    "dev-server": "nodemon --exec babel-node src/server/server.js --ignore dist/",
    "test": "jest tests"
  },
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.9.6",
    "@babel/node": "^7.8.7",
    "babel-loader": "^8.1.0",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.7",
    "sequelize-cli": "^5.5.1"
  },
  "devDependencies": {
    "jest": "^25.5.4",
    "nodemon": "^2.0.3"
  }
}

And here was the runner that threw the error:

这是抛出错误的跑步者:

nodemon --exec babel-node src/server/server.js --ignore dist

This was frustrating, as I had a similar Express project that worked fine.

这令人沮丧,因为我有一个运行良好的类似 Express 项目。

The solution was firstly to add this dependency:

解决方案是首先添加此依赖项:

npm install @babel/preset-env

And then to wire it in using a babel.config.jsin the project root:

然后babel.config.js在项目根目录中使用 a 连接它:

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

I don't fully grok why this works, but I copied it from an authoritative source, so I am happy to stick with it.

我不完全理解为什么会这样,但我从权威来源复制了它,所以我很乐意坚持下去。

回答by ishab acharya

My solution was to include babel-node path while running nodemon as follows:

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

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

you can add in your package.json script as :

您可以将 package.json 脚本添加为:

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

NOTE: My entry file is index.jsreplace it with your entry file(many have app.js/server.js).

注意:我的入口文件是index.js,用你的入口文件替换它(许多有 app.js/server.js)。