Reputation: 707
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
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:
npm install eslint-plugin-regex
{
"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";
{
"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
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