如何在 eslintrc 文件中使用导入?

Kar*_*ius 1 javascript eslint

我尝试使用导入的对象为 .eslintrc.js 文件内的全局变量设置一些限制,但导入不起作用。我如何进行动态 eslint 配置?

import {loadedGlobals} from '@/util/globals'                      

module.exports = {
    'globals': Object.keys(loadedGlobals).reduce((acum, key) => {
        acum[key] = false
        return acum
    }, acum),
    // ...
}
Run Code Online (Sandbox Code Playgroud)

mor*_*ney 6

更新:

使用新的配置系统,您可以使用package.json 中的eslint.config.js文件来支持语句。"type": "module"import

此外,如果您需要从 CJS 上下文加载 ESM 模块,配置文件可以导出 Promise,以便您可以在函数await import内运行async

async function config () {
  const dep = await import('esm-dep')
  return [dep]
}
module.exports = config()
Run Code Online (Sandbox Code Playgroud)

目前支持导出承诺的功能,只是尚未记录。更新的文档已合并,只是尚未发布。

-c eslint.config.mjs通过文件扩展名支持模块系统上下文的节点版本方法还有一个隐藏的宝石。

原来的:

如何在 eslintrc 文件中使用导入?

ESLint 目前不支持名为 的配置文件eslintrc,所以我假设您的意思是.eslintrc.js.

ESLint 目前不支持 ES 模块,您可以从其配置文件格式文档上的JavaScript (ESM)项目符号项中看到。

如果您愿意安装另一个依赖项,请在import以下位置使用.eslintrc.js

  1. 安装esm模块,npm i esm -D(这里我选择为devDependency)。
  2. 创建一个新文件作为名为 的同级.eslintrc.js文件.eslintrc.esm.js
  3. 里面.eslintrc.esm.js包含你的 ESLint 配置。您可以在此处使用import,并且应该将配置导出为export default { // Your config }.
  4. 里面.eslintrc.js包含以下代码:
const _require = require('esm')(module)
module.exports = _require('./.eslintrc.esm').default
Run Code Online (Sandbox Code Playgroud)

现在您应该可以eslint像平常一样运行了。额外的文件有点笨重,但如果您愿意,可以将它们组织在一个目录中,并使用指向新位置--config的选项。eslint