Remove unused imports

JavaScript pattern

This pattern removes unused imports of top level modules like import React from "react" or import * as lodash from "lodash".


Apply with the Grit CLI
grit apply unused_imports

Test case: jsx-element

BEFORE
import * as React from "react";

<div>Hi</div>;
AFTER
<div>Hi</div>

Test case: jsx-fragment

BEFORE
import * as React from "react";

<></>;
AFTER
<></>

Test case: react-not-removed

JAVASCRIPT
import React from "react";

React.createElement("div", {});

Promise.resolve(React);

<div>Hi</div>;

Test case: variable-already-used

JAVASCRIPT
import * as React from "react";

React.createElement("div", {});

createElement("someFunction");

<div>Hi</div>;

Test case: default-and-multiple-specifiers-import-react-variable

JAVASCRIPT
import React, { useState } from "react";

React.createElement("div", {});
useState();

<div>Hi</div>;

Test case: default-and-multiple-specifiers-import

BEFORE
import React, { type Element, createElement, useState } from "react";

const element: Element = createElement();
<div>Hi</div>;
AFTER
import { type Element, createElement } from "react";

const element: Element = createElement();
<div>Hi</div>;

Test case: leading-comment

BEFORE
/**
 * Hello world.
 */

import * as React from "react";

<div></div>;
AFTER
/**
 * Hello world.
 */

<div></div>

Test case: react-already-used-named-export

JAVASCRIPT
import * as React from "react";

React.useState(false);

Test case: react-basic-default-export-jsx-element-react-variable

JAVASCRIPT
import React from "react";

React.createElement("div", {});

<div></div>;

Test case: react-basic-default-export-jsx-element

BEFORE
import React from "react";

<div></div>;
AFTER
<div></div>

Test case: react-basic-default-export

JAVASCRIPT
import React from "react";

React.createElement("div", "la");

Test case: react-jsx-member-expression

JAVASCRIPT
import React from "react";

<React.Fragment />;

Test case: react-type-default-export

BEFORE
import type React from "react";
import * as React from "react";

<div>Hi</div>;
AFTER
<div>Hi</div>;