简体   繁体   English

ESLint - 错误:必须使用导入来加载 ES 模块

[英]ESLint - Error: Must use import to load ES Module

I am currently setting up a boilerplate with React, TypeScript, styled components, Webpack , etc., and I am getting an error when trying to run ESLint :我目前正在使用 React、TypeScript、样式化组件、 Webpack等设置样板,在尝试运行ESLint时出现错误:

Error: Must use import to load ES Module错误:必须使用 import 来加载 ES 模块

Here is a more verbose version of the error:这是错误的更详细版本:

/Users/ben/Desktop/development projects/react-boilerplate-styled-context/src/api/api.ts
  0:0  error  Parsing error: Must use import to load ES Module: /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js
require() of ES modules is not supported.
require() of /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/babel-eslint/lib/require-from-eslint.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename definition.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/package.json

The error occurs in every single one of my.js and.ts/.tsx files where I only use import or the file doesn't even have an import at all. my.js 和 .ts/.tsx 文件中的每一个都发生错误,我只使用import或者文件甚至根本没有导入。 I understand what the error is saying, but I don't have any idea why it is being thrown when in fact I only use imports or even no imports at all in some files.我明白错误在说什么,但我不知道为什么会抛出它,而实际上我在某些文件中只使用导入甚至根本不使用导入。

Here is my package.json file where I trigger the linter from using npm run lint:eslint:quiet :这是我的package.json文件,我在其中使用npm run lint:eslint:quiet触发 linter:

{
  "name": "my-react-boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.tsx",
  "directories": {
    "test": "test"
  },
  "engines": {
    "node": ">=14.0.0"
  },
  "type": "module",
  "scripts": {
    "build": "webpack --config webpack.prod.js",
    "dev": "webpack serve --config webpack.dev.js",
    "lint": "npm run typecheck && npm run lint:css && npm run lint:eslint:quiet",
    "lint:css": "stylelint './src/**/*.{js,ts,tsx}'",
    "lint:eslint:quiet": "eslint --ext .ts,.tsx,.js,.jsx  ./src --no-error-on-unmatched-pattern --quiet",
    "lint:eslint": "eslint --ext .ts,.tsx,.js,.jsx  ./src --no-error-on-unmatched-pattern",
    "lint:eslint:fix": "eslint --ext .ts,.tsx,.js,.jsx  ./src --no-error-on-unmatched-pattern --quiet --fix",
    "test": "cross-env NODE_ENV=test jest --coverage",
    "test:watch": "cross-env NODE_ENV=test jest --watchAll",
    "typecheck": "tsc --noEmit",
    "precommit": "npm run lint"
  },
  "lint-staged": {
    "*.{ts,tsx,js,jsx}": [
      "npm run lint:eslint:fix",
      "git add --force"
    ],
    "*.{md,json}": [
      "prettier --write",
      "git add --force"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "npx lint-staged && npm run typecheck"
    }
  },
  "resolutions": {
    "styled-components": "^5"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.5.4",
    "@babel/plugin-proposal-class-properties": "^7.5.0",
    "@babel/preset-env": "^7.5.4",
    "@babel/preset-react": "^7.0.0",
    "@types/history": "^4.7.6",
    "@types/react": "^17.0.29",
    "@types/react-dom": "^17.0.9",
    "@types/react-router": "^5.1.17",
    "@types/react-router-dom": "^5.1.5",
    "@types/styled-components": "^5.1.15",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "babel-cli": "^6.26.0",
    "babel-eslint": "^10.0.2",
    "babel-loader": "^8.0.0-beta.6",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "clean-webpack-plugin": "^4.0.0",
    "dotenv-webpack": "^7.0.3",
    "error-overlay-webpack-plugin": "^1.0.0",
    "eslint": "^8.0.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-config-with-prettier": "^6.0.0",
    "eslint-plugin-compat": "^3.3.0",
    "eslint-plugin-import": "^2.25.2",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.14.2",
    "eslint-plugin-react-hooks": "^4.2.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.2",
    "husky": "^7.0.2",
    "prettier": "^2.4.1",
    "raw-loader": "^4.0.2",
    "style-loader": "^3.3.0",
    "stylelint": "^13.13.1",
    "stylelint-config-recommended": "^5.0.0",
    "stylelint-config-styled-components": "^0.1.1",
    "stylelint-processor-styled-components": "^1.10.0",
    "ts-loader": "^9.2.6",
    "tslint": "^6.1.3",
    "typescript": "^4.4.4",
    "url-loader": "^4.1.1",
    "webpack": "^5.58.2",
    "webpack-cli": "^4.2.0",
    "webpack-dev-server": "^4.3.1",
    "webpack-merge": "^5.3.0"
  },
  "dependencies": {
    "history": "^4.10.0",
    "process": "^0.11.10",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "styled-components": "^5.2.1"
  }
}

Here is my.eslintrc file:这是 my.eslintrc 文件:

{
  "extends": ["airbnb", "prettier"],
  "parser": "babel-eslint",
  "plugins": ["prettier", "@typescript-eslint"],
  "parserOptions": {
    "ecmaVersion": 8,
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "impliedStrict": true,
      "classes": true
    }
  },
  "env": {
    "browser": true,
    "node": true,
    "jest": true
  },
  "rules": {
    "arrow-body-style": ["error", "as-needed"],
    "class-methods-use-this": 0,
    "react/jsx-filename-extension": 0,
    "global-require": 0,
    "react/destructuring-assignment": 0,
    "import/named": 2,
    "linebreak-style": 0,
    "import/no-dynamic-require": 0,
    "import/no-named-as-default": 0,
    "import/no-unresolved": 2,
    "import/prefer-default-export": 0,
    "semi": [2, "always"],
    "max-len": [
      "error",
      {
        "code": 80,
        "ignoreUrls": true,
        "ignoreComments": true,
        "ignoreStrings": true,
        "ignoreTemplateLiterals": true
      }
    ],
    "new-cap": [
      2,
      {
        "capIsNew": false,
        "newIsCap": true
      }
    ],
    "no-param-reassign": 0,
    "no-shadow": 0,
    "no-tabs": 2,
    "no-underscore-dangle": 0,
    "react/forbid-prop-types": [
      "error",
      {
        "forbid": ["any"]
      }
    ],
    "import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
    "react/jsx-no-bind": [
      "error",
      {
        "ignoreRefs": true,
        "allowArrowFunctions": true,
        "allowBind": false
      }
    ],
    "react/no-unknown-property": [
      2,
      {
        "ignore": ["itemscope", "itemtype", "itemprop"]
      }
    ]
  }
}

And I'm not sure if it is relevant, but here is also my tsconfig.eslint.json file:我不确定它是否相关,但这也是我的tsconfig.eslint.json文件:

{
  "extends": "./tsconfig.json",
  "include": ["./src/**/*.ts", "./src/**/*.tsx", "./src/**/*.js"],
  "exclude": ["node_modules/**", "build/**", "coverage/**"]
}

How can I fix this?我怎样才能解决这个问题?

Googling the error does not present any useful forums or raised bugs.谷歌搜索错误不会出现任何有用的论坛或引发的错误。 Most of them just state not to use require in your files which I am not.他们中的大多数只是 state 不要在你的文件中使用require我不是。

I think the problem is that you are trying to use the deprecated babel-eslint parser , last updated a year ago, which looks like it doesn't support ES6 modules.我认为问题在于您正在尝试使用已弃用的babel-eslint parser ,上次更新是一年前,看起来它不支持 ES6 模块。 Updating to the latest parser seems to work, at least for simple linting.更新到最新的解析器似乎有效,至少对于简单的 linting。

So, do this:所以,这样做:

  • In package.json, update the line "babel-eslint": "^10.0.2", to "@babel/eslint-parser": "^7.5.4", .在 package.json 中,将"babel-eslint": "^10.0.2",行更新为"@babel/eslint-parser": "^7.5.4", This works with the code above but it may be better to use the latest version, which at the time of writing is 7.16.3.这适用于上面的代码,但使用最新版本可能会更好,在撰写本文时它是 7.16.3。
  • Run npm i from a terminal/command prompt in the folder从文件夹中的终端/命令提示符运行npm i
  • In .eslintrc, update the parser line "parser": "babel-eslint", to "parser": "@babel/eslint-parser",在 .eslintrc 中,将解析器行"parser": "babel-eslint",更新为"parser": "@babel/eslint-parser",
  • In .eslintrc, add "requireConfigFile": false, to the parserOptions section (underneath "ecmaVersion": 8, ) (I needed this or babel was looking for config files I don't have)在 .eslintrc 中,将"requireConfigFile": false,添加到 parserOptions 部分(在"ecmaVersion": 8,下方)(我需要这个或 babel 正在寻找我没有的配置文件)
  • Run the command to lint a file运行命令对文件进行 lint

Then, for me with just your two configuration files, the error goes away and I get appropriate linting errors.然后,对我来说只有你的两个配置文件,错误消失了,我得到了适当的 linting 错误。

This can happen with quite a lot of lately released frameworks like VueJS or Nuxt, mostly because of the usage of ESM modules (not fully or at all supported by older Node.js versions).这可能发生在很多最近发布的框架上,比如 VueJS 或 Nuxt,主要是因为使用了 ESM 模块(旧的 Node.js 版本不完全或根本不支持)。

The fastest approach for this is to use something like nvm , after installing it, you could run:最快的方法是使用类似nvm的东西,在安装它之后,你可以运行:

  • nvm i 16 (v16 is the latest LTS as of time of writing) nvm i 16 (v16 是撰写本文时最新的 LTS)
  • nvm use 16

And you'll be running the project with a full ESM support.您将在完全支持 ESM 的情况下运行该项目。
You can double check that by running node -v .您可以通过运行node -v来仔细检查。

Create React App 2021-November创建 React App 2021-11 月

Error错误

Error: Must use import to load ES Module错误:必须使用导入来加载 ES 模块

To fix the error, I did the following:为了修复该错误,我执行了以下操作:

1. Eject the configuration file and dependencies 1. 弹出配置文件和依赖

Note: this is a one-way operation.注意:这是一种单向操作。 Once you eject , you can't go back!一旦eject ,就回不去了!

yarn eject

2. Remove babel-eslint and babel-preset-react-app 2. 移除babel-eslintbabel-preset-react-app

Delete babel-eslint and babel-preset-react-app :删除babel-eslintbabel-preset-react-app

package.json包.json

  "devDependencies": {
    ...
    "babel-eslint": "^10.1.0",  <-- DELETE
    "babel-preset-react-app": "^10.0.0",  <-- DELETE

3. Add @babel/eslint-parser and @babel/preset-react 3. 添加@babel/eslint-parser@babel/preset-react

Add the latest versions of @babel/eslint-parser and @babel/preset-react :添加最新版本的@babel/eslint-parser@babel/preset-react

package.json包.json

  "devDependencies": {
    ...
    "@babel/eslint-parser": "^7.16.3",  <-- ADD
    "@babel/preset-react": "^7.16.0",  <-- ADD

4. Add "parser": "@babel/eslint-parser" 4.添加"parser": "@babel/eslint-parser"

Find the key eslintConfig in package.json and add "parser": "@babel/eslint-parser" :package.json 中找到 key eslintConfig并添加"parser": "@babel/eslint-parser"

  ...
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ],
    "parser": "@babel/eslint-parser"
  },

5. Update npm dependencies 5. 更新 npm 依赖

yarn install

在 Visual Studio 代码中,删除 Eslint 扩展,然后重新安装。

For React Native setup using eslint-config-react-native-community package对于使用eslint-config-react-native-community 包的React Native 设置

I did what the accepted answer suggesting to do but I had no "babel-eslint": "^10.0.2", line in my package.json of the root folder.我做了接受的答案建议做的事情,但我的根文件夹的package.json中没有"babel-eslint": "^10.0.2",行。

  • Go to node_modules/@react-native-community/eslint-config转到node_modules/@react-native-community/eslint-config
  • Edit package.json, change "babel-eslint": "^10.0.2", to "@babel/eslint-parser": "^7.18.2",编辑 package.json,将"babel-eslint": "^10.0.2",改为"@babel/eslint-parser": "^7.18.2",
  • Edit index.js, change "parser": "babel-eslint", to parser: '@babel/eslint-parser',编辑 index.js,将"parser": "babel-eslint",改为parser: '@babel/eslint-parser',
  • Go to root folder of your project and npm i -D @babel/eslint-parser转到项目的根文件夹和npm i -D @babel/eslint-parser
  • Run the lint command运行 lint 命令

It worked for me this way.它以这种方式对我有用。

I followed @rich-n advice from a comment above, and according to this :我从上面的评论中遵循了@rich-n 的建议,并据此

go to .eslintrc.js and make sure you have the following settings: go 到.eslintrc.js并确保您具有以下设置:

module.exports = {
  parser: "@babel/eslint-parser",
  parserOptions: {
    requireConfigFile: false,
    babelOptions: {
      babelrc: false,
      configFile: false,
      // your babel options
      presets: ["@babel/preset-env"],
    },
  },
};

doing this removed all the "red" marks from vscode:)这样做从 vscode 中删除了所有“红色”标记:)

The problem can be easily resolved by changing the file extension of.eslintrc from js to json (exporting the.eslintrc object using ESM format in.eslintrc.js just doesn't work).通过将.eslintrc的文件扩展名从js更改为json可以轻松解决该问题(使用ESM格式在.eslintrc.js中导出.eslintrc object只是不起作用)。

If you did all above and still fails, reload your vscode.如果您执行了上述所有操作但仍然失败,请重新加载您的 vscode。

I just delete node_modules , and re installed through npm install , and now it works.我只是删除node_modules ,并通过npm install重新安装,现在它可以工作了。

Faced a similar error while using reactful by Samer Buna.在使用 Samer Buna 的reactful 时遇到了类似的错误。 Resolved by following the directions at Rich N's answer .按照 Rich N's answer 中的说明解决

"@babel/eslint-parser" depends on "@babel/core". “@babel/eslint-parser”依赖于“@babel/core”。 So after "npm install @babel/eslint-parser -S", u should npm i @babel/core -S所以在“npm install @babel/eslint-parser -S”之后,你应该npm i @babel/core -S

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM