Bertie92
Bertie92

Reputation: 707

How to disallow empty imports in eslint?

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.)

Upvotes: 1

Views: 966

Answers (2)

DragonsGamers
DragonsGamers

Reputation: 51

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

Upvotes: 1

Farzad
Farzad

Reputation: 283

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.

Upvotes: 3

Related Questions