如何配置ESLint-plugin-import检测CommonJS导出的缺失属性?
如何让ESLint检测CommonJS导出中不存在的导入成员?
问题背景
我有两个JS文件:
abc.js
// abc.js module.exports = { def: 7, ghi: 8, } // export const def = 7 // export const ghi = 8
importing.js
// importing.js import { xyz } from './abc.js'
当前遇到的情况:
- WebStorm能自动识别
xyz不存在于abc.js的module.exports对象中并给出警告 - 搭配
eslint-plugin-import的ESLint却没有任何报错 - 但把
abc.js改成ES6命名导出(注释里的写法)时,ESLint能正常触发import/named规则报错
我当前的ESLint规则配置如下:
{ 'import/no-unresolved': [2, {commonjs: true, amd: true}], 'import/named': 2, 'import/no-named-as-default': 2, 'import/no-named-default': 2, }
解决方案
eslint-plugin-import的import/named规则只针对ES6原生命名导出做校验,没办法识别CommonJS导出对象里的属性。要检测这种从CommonJS模块导入不存在属性的场景,需要借助专门的插件:
- 首先安装
eslint-plugin-commonjs插件:
npm install eslint-plugin-commonjs --save-dev
- 在ESLint配置中添加插件并启用对应的规则:
module.exports = { // ...其他原有配置 plugins: ['import', 'commonjs'], // 新增commonjs插件 rules: { // ...你已有的规则 'commonjs/no-unresolved-exports': 2 // 启用该规则,值2表示报错级别 } }
启用这个规则后,ESLint就能检测到从CommonJS模块导入不存在的成员,并给出相应报错。
内容的提问来源于stack exchange,提问作者v-moe
相关产品推荐
相关产品推荐

