1

I've been trying to disallow empty imports like this:

import {} from 'module-foo'; 

Does anybody know how to do it? (I have a TypeScript Node.js project.)

2
  • I suppose that would belong in npmjs.com/package/eslint-plugin-import, but it doesn't look like it has that rule now. Commented Jun 10, 2021 at 9:35
  • @jonrsharpe Thanks, I am using this plugin already, but I haven't found a rule for this either. Commented Jun 10, 2021 at 9:38

2 Answers 2

3

Although there are no predefined rules for it, you can use no-restricted-syntax rule and AST Selectors to disallow this certain syntax:

// .eslintrc.js module.exports = { // ... rest of the options rules: { // ... rest of the rules 'no-restricted-syntax': [ 'error', { selector: 'ImportDeclaration[specifiers.length = 0]', message: 'Empty imports are not allowed', }, ], } } 

Check this AST Tree to understand how the selector is targeting empty import.

Sign up to request clarification or add additional context in comments.

1 Comment

in my case, i wanted to allow only empty imports for styles, so I ended up using this selector ImportDeclaration[specifiers.length = 0][source.value!=/\\.s?css$/]. seems to work great.
1

Farzad's solution gave me some problems like false positive or does not work in:

import "package"; import PackageDefault, {} from "package"; 

I solved it with:

  1. Run
npm install eslint-plugin-regex 
  1. Change you eslintrc
{ "plugins": [ "regex" ], "rules": { "regex/invalid": [ "error", [ { "id": "EmptyImport", "message": "errorMessageN", "regex": "import(.*{\\s*}.*)from", "replacement": { "function": "return $[1].replace(/\\s/g, '') !== '{}' ? $[0].replace(/,?\\s{\\s*},?\\s/, ' ') : $[0]" } } ] ], } } 
### This rule suport eslint --fix 
import {} from "package"; // manual fixable import package, {} from "package"; // import package from "package"; 

to automatically remove import voids during eslint fix:

import {} from "package"; 
  1. Use this rule in place of the other
{ "id": "EmptyImport", "message": "errorMessageN", "regex": "import(.*{\\s*}.*)from.*\\n", "replacement": { "function": "return $[1].replace(/\\s/g, '') !== '{}' ? $[0].replace(/,?\\s{\\s*}\\s/, ' ') : ''" } } 

Solution in MyLinter Package: ❤️ https://github.com/ODGodinho/ODG-Linter-Js/blob/cd4a67afc45f624ee34abab7814b7a245e5c00ad/rules/javascript/possible-errors.js#L36

you can download it if you want, it will avoid these and other errors: https://www.npmjs.com/package/@odg/eslint-config#installation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.