3

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,297
  • 2
  • 11
  • 31
  • Loosely related: for VS Code users, you might want to change the value of `typescript.preferences.importModuleSpecifier` (see [Is it possible to configure vs code such way that import will use absolute path (not relative)?](https://stackoverflow.com/q/47330773/11107541)). – starball Dec 21 '22 at 07:24

2 Answers2

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
  • 460
  • 2
  • 7
  • 1
    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
0

I also faced this problem and created an ESLint plugin to solve it. You can find it here: https://github.com/qDanik/eslint-plugin-path

starball
  • 20,030
  • 7
  • 43
  • 238