Skip to content

Instantly share code, notes, and snippets.

@IanVS
Last active March 14, 2023 22:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanVS/f18e5032f5ab99d25fd68bae01acd541 to your computer and use it in GitHub Desktop.
Save IanVS/f18e5032f5ab99d25fd68bae01acd541 to your computer and use it in GitHub Desktop.
Custom eslint rule to prevent default import of React.
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.',
});
}
}
},
};
},
};
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