Last active
August 14, 2024 18:13
-
-
Save IanVS/f18e5032f5ab99d25fd68bae01acd541 to your computer and use it in GitHub Desktop.
Custom eslint rule to prevent default import of React.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
meta: { | |
type: 'suggestion', | |
fixable: 'code', | |
schema: [], | |
}, | |
create(context) { | |
return { | |
ImportDeclaration(node) { | |
if ( | |
node.source.value === 'react' && | |
// Only look for imports of react itself, not `import type` | |
node.importKind === 'value' | |
) { | |
// If there's only one default import, we can make an autofix | |
if (node.specifiers.length === 1 && node.specifiers[0].type === 'ImportDefaultSpecifier') { | |
context.report({ | |
node, | |
message: 'Do not use the default React import, use named or namespace import instead.', | |
fix(fixer) { | |
return fixer.replaceText(node.specifiers[0], '* as React'); | |
}, | |
}); | |
} | |
// Mixing default and named imports, cannot autofix | |
else if (node.specifiers.some((specifier) => specifier.type === 'ImportDefaultSpecifier')) { | |
context.report({ | |
node, | |
message: 'Do not use the default React import, use named or namespace import instead.', | |
}); | |
} | |
} | |
}, | |
}; | |
}, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const rule = require('./no-react-default-import'); | |
const RuleTester = require('eslint').RuleTester; | |
const ruleTester = new RuleTester({ | |
parser: require.resolve('@typescript-eslint/parser'), | |
}); | |
ruleTester.run('no-react-default-import', rule, { | |
valid: [ | |
{ | |
code: 'import * as React from "react";', | |
}, | |
{ | |
code: 'import React from "preact";', | |
}, | |
{ | |
code: 'import {useState} from "react";', | |
}, | |
{ | |
code: 'import type React from "react";', | |
}, | |
{ | |
code: 'const React = require("react");', | |
}, | |
], | |
invalid: [ | |
{ | |
code: 'import React from "react";', | |
errors: [{ message: 'Do not use the default React import, use named or namespace import instead.' }], | |
output: 'import * as React from "react";', | |
}, | |
{ | |
code: 'import React, {useState} from "react";', | |
errors: [{ message: 'Do not use the default React import, use named or namespace import instead.' }], | |
}, | |
], | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment