配置ESLint浏览器全局变量时出现空格错误求助
解决ESLint配置浏览器全局变量时的"AudioWorkletGlobalScope "空格错误
我按照ESLint官方文档在eslint.config.js中配置浏览器全局变量,代码如下:
import eslint from "@eslint/js"; import globals from "globals"; export default [ { languageOptions: { globals: { ...globals.browser } } }, { files: ["**/*.js", "**/*.cjs", "**/*.mjs"], rules: eslint.configs.recommended.rules }, { ignores: ["rollup.config.js", "web-test-runner.config.js", "src/index.bundle.js"] } ]
运行ESLint时出现以下错误:
Oops! Something went wrong! :( ESLint: 9.11.1 TypeError: Key "languageOptions": Key "globals": Global "AudioWorkletGlobalScope " has leading or trailing whitespace. at new Config (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/config/config.js:211:23) at [finalizeConfig] (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/config/flat-config-array.js:216:16) at FlatConfigArray.getConfigWithStatus (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@eslint/config-array/dist/cjs/index.cjs:1102:55) at FlatConfigArray.getConfig (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@eslint/config-array/dist/cjs/index.cjs:1120:15) at /Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/eslint/eslint-helpers.js:346:56 at Array.reduce (<anonymous>) at /Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/eslint/eslint-helpers.js:333:36 at /Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/eslint/eslint-helpers.js:296:32 at Object.isAppliedFilter (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@nodelib/fs.walk/out/readers/common.js:12:31) at AsyncReader._handleEntry (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@nodelib/fs.walk/out/readers/async.js:86:20)
解决方法
这个错误是因为globals包的旧版本中,browser全局变量集合里的AudioWorkletGlobalScope名称末尾带有空格,而ESLint 9+会严格校验全局变量名称格式,不允许包含前后空格。
你可以通过以下两种方式解决:
更新
globals包到最新版本
该问题已在globals包的后续版本中修复,执行命令更新:npm update globals # 或使用yarn yarn upgrade globals更新后重新运行ESLint即可。
手动处理带空格的全局变量(临时方案)
如果暂时无法更新包,可以手动修正变量名的空格问题:import eslint from "@eslint/js"; import globals from "globals"; // 去除全局变量名称中的前后空格 const cleanedBrowserGlobals = Object.fromEntries( Object.entries(globals.browser).map(([key, value]) => [key.trim(), value]) ); export default [ { languageOptions: { globals: cleanedBrowserGlobals } }, { files: ["**/*.js", "**/*.cjs", "**/*.mjs"], rules: eslint.configs.recommended.rules }, { ignores: ["rollup.config.js", "web-test-runner.config.js", "src/index.bundle.js"] } ]
内容的提问来源于stack exchange,提问作者Ole
相关产品推荐
相关产品推荐

