Skip to content

Instantly share code, notes, and snippets.

@ryohey
Last active October 28, 2020 15:16
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 ryohey/356430d6dc55456d8b3c6561cd89b7bc to your computer and use it in GitHub Desktop.
Save ryohey/356430d6dc55456d8b3c6561cd89b7bc to your computer and use it in GitHub Desktop.
convert absolute import to relative
const fs = require("fs")
const child_process = require("child_process")
const readdirRecursively = (dir, files = []) => {
const paths = fs.readdirSync(dir)
const dirs = []
for (const path of paths) {
const stats = fs.statSync(`${dir}/${path}`)
if (stats.isDirectory()) {
dirs.push(`${dir}/${path}`)
} else {
files.push(`${dir}/${path}`)
}
}
for (const d of dirs) {
files = readdirRecursively(d, files)
}
return files
}
const files = readdirRecursively("src")
for (let file of files) {
const cmd = `node relimport ${file}`
console.log(cmd)
child_process.execSync(cmd)
}
const path = require("path")
const fs = require("fs")
const filePath = path.resolve(process.argv[2])
const inputText = fs.readFileSync(filePath, "utf-8")
const mappings = [
["common", "src"],
["main", "src"],
["components", "src/main"],
]
const fixImports = (filePath, txt) => {
const regexp = /^import .+ from "(.+)"$/gm
/*
0: "import { NoteCoordTransform } from "common/transform""
1: " NoteCoordTransform "
2: "common/transform"
*/
let match
let tmpText = txt
while ((match = regexp.exec(txt)) !== null) {
const importPath = match[1]
for (let map of mappings) {
if (importPath.startsWith(map[0])) {
const absImportPath = path.resolve(__dirname, map[1], importPath)
const fixedPath = path.relative(path.dirname(filePath), absImportPath)
const fixedImport = match[0].replace(importPath, fixedPath)
console.log(match[0], "to", fixedImport)
tmpText = tmpText.replace(match[0], fixedImport)
break
}
}
}
return tmpText
}
const newText = fixImports(filePath, inputText)
fs.writeFileSync(filePath, newText)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment