Skip to content

Instantly share code, notes, and snippets.

@gaving
Last active January 19, 2021 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaving/631857b7babb23189c0d98a89e1cf5e3 to your computer and use it in GitHub Desktop.
Save gaving/631857b7babb23189c0d98a89e1cf5e3 to your computer and use it in GitHub Desktop.
import-icons-by-path

Description

Convert Material UI icons to path imports. E.g.

-import { ErrorOutline as ErrorIcon } from "@material-ui/icons";
+import ErrorIcon from "@material-ui/icons/ErrorOutline";

Reasoning:-

  • This reduces development time as react-scripts is faster to start and smaller bundle sizes.
  • Any icon not imported in this fashion has the side effect of the entire icon library being imported.
  • Production builds i.e. react-scripts build are not affected as treeshaking occurs normally.

Usage

jscodeshift -v 2 -t ./transform.js src

Example

Development bundle sizes before and after conversion to path imports.

└── [ 160]  before
|   ├── [ 19M]  0.chunk.js
|   ├── [ 35K]  bundle.js
|   └── [1.5M]  main.chunk.js
├── [ 160]  after
    ├── [9.3M]  0.chunk.js
    ├── [ 35K]  bundle.js
    └── [1.5M]  main.chunk.js

21M vs 11M difference.

Launching

Before

yarn start  0.21s user 0.04s system 1% cpu 13.801 total

After

yarn start  0.30s user 0.06s system 1% cpu 30.274 total

Refs

export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.ImportDeclaration)
.forEach((path) => {
const pathStr = path.value.source.value;
if (pathStr.startsWith("@material-ui/icons")) {
path.value.specifiers.forEach((spec) => {
let newPath = pathStr.replace(
/^@material-ui(.*(?=\/))?/,
"@material-ui/icons"
);
if (spec.imported) {
newPath = "@material-ui/icons/" + spec.imported.name;
}
path.insertBefore(
j.importDeclaration(
[j.importDefaultSpecifier(spec.local)],
j.literal(newPath)
)
);
});
path.replace();
}
})
.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment