Skip to content

Instantly share code, notes, and snippets.

@dkarter
Created June 28, 2022 20:00
Show Gist options
  • Save dkarter/0bf9d615db8fad1fcbdf33c003ba23ee to your computer and use it in GitHub Desktop.
Save dkarter/0bf9d615db8fad1fcbdf33c003ba23ee to your computer and use it in GitHub Desktop.
Migrate TypeScript/Javascript projects from relative to absolute paths
relative_to_absolute = fn relative_path, importing_file ->
Path.expand(relative_path, Path.dirname(importing_file))
|> String.split("src/")
|> List.last()
end
Path.wildcard('src/**/*.{ts,tsx}')
|> Enum.each(fn file ->
IO.puts("Migrating #{file}...")
contents = File.read!(file)
migrated =
contents
|> String.split("\n")
|> Enum.map(fn line ->
Regex.replace(~r/from '(\.\.\/.+?)';/, line, fn _match, relative_path ->
"from '#{relative_to_absolute.(relative_path, file)}';"
end)
end)
|> Enum.join("\n")
File.write!(file, migrated)
IO.puts("DONE")
end)
@dkarter
Copy link
Author

dkarter commented Jun 28, 2022

Example tsconfig:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDir": ".",
    "baseUrl": "src",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "jsx": "react",
    "types": ["jest"],
    "typeRoots": ["./types", "./node_modules/@types"],
    "paths": {
      "__tests__/*": ["../__tests__/*"]
    }
  },
  "exclude": ["coverage"]
}

Notably the baseUrl is set to src which is where all the imported files live.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment