Skip to content

Instantly share code, notes, and snippets.

@gaving
Last active January 19, 2021 19:38
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/df16abac5ccda68196f0d587767fd8f2 to your computer and use it in GitHub Desktop.
Save gaving/df16abac5ccda68196f0d587767fd8f2 to your computer and use it in GitHub Desktop.
convert-to-absolute-imports

Description

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

-import DashboardTitle from "../../../components/Dashboard/DashboardTitle";
+import DashboardTitle from "components/Dashboard/DashboardTitle";

Reasoning:-

  • Combined with jsconfig.json file reduces path complexity

Usage

git reset head --hard && jscodeshift -v 2 -t ./transform.js src

Refs

{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
const path = require("path");
const SOURCE = "src";
const SOURCE_PATH = path.resolve(SOURCE) + "/";
const removeSourceDirName = (path) =>
path.replace(new RegExp(`^${SOURCE}\/?`, "gi"), "");
const getAbsolutePath = (importPath, filePath) => {
if (!importPath.startsWith(".")) {
return importPath;
}
return path
.resolve(path.dirname(filePath), importPath)
.replace(SOURCE_PATH, "");
};
const replaceImportPath = (j, node, filePath) =>
j.importDeclaration(
node.value.specifiers,
j.literal(getAbsolutePath(node.value.source.value, filePath))
);
export default function (file, api) {
const j = api.jscodeshift;
const filePath = file.path;
return j(file.source)
.find(j.ImportDeclaration)
.replaceWith((node) => replaceImportPath(j, node, filePath))
.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment