2

I am trying to rewrite all existing relative paths in my javascript/typescript project to absolute paths.

Example:

import example from "../../example"

would be rewritten to

import example from "src/components/example" 

So I am looking for a script or similar to transform all these imports. Preferably it would be possible to run this as an npm script on precommit or similar.

Is there a way to do this?

Henning Hall
  • 1,165
  • 1
  • 9
  • 28

1 Answers1

0

It looks like imports are done for static analysis and cannot truly be dynamic (Importing modules using ES6 syntax and dynamic path). I am wondering though if you can do something in the tsconfig.json to accomplish this. Under the "compilerOptions: { ..., "paths": { "@components/": "src/components/". I am not sure this will solve your use case but it may be worth a try. So your import would look like:

import { example } from "@components/example"

Paul
  • 415
  • 2
  • 7
  • To be clear, the imports work as it is. I just need to rewrite all imports in the existing codebase automatically. – Henning Hall Nov 06 '19 at 11:20
  • I think the example I provided will rewrite your import statements to map the paths of the imports to the key / value pair, so the compiler will transform anywhere the import has @components in the path to src/components. I can see the problem being if you have directories within the components directory. – Paul Nov 06 '19 at 11:32