Relative imports of files from same folder are edited in WebStorm

Relative Imports of Files from Same Folder are Edited in WebStorm

When working with TypeScript in WebStorm, you may encounter a situation where relative imports of files from the same folder are automatically edited by the IDE. This can be frustrating, especially if you have a specific folder structure or naming convention that you want to maintain. In this blog post, we will explore a couple of solutions to this problem.

Solution 1: Configure WebStorm

The first solution involves configuring WebStorm to prevent it from automatically editing relative imports. Follow these steps:

  1. Open the WebStorm settings by going to File > Settings (or WebStorm > Preferences on macOS).
  2. Navigate to Editor > Code Style > TypeScript.
  3. Click on the “Imports” tab.
  4. Uncheck the “Use path mapping” option.
  5. Click “Apply” and then “OK” to save the changes.

By disabling the “Use path mapping” option, WebStorm will no longer automatically edit relative imports.

Solution 2: Use TypeScript Path Mapping

If you still want to use path mapping but want to maintain your specific folder structure, you can use TypeScript’s path mapping feature. This allows you to define custom import paths that map to specific folders.

To use TypeScript path mapping, follow these steps:

  1. Create a tsconfig.json file in the root of your project if you don’t already have one.
  2. Add the following configuration to the tsconfig.json file:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

In this example, we’re mapping the @/* import path to the src/* folder. You can customize this mapping to match your specific folder structure.

Now, you can use the path mapping in your imports:

import { MyClass } from '@/myClass';

With TypeScript path mapping, WebStorm will recognize and respect the custom import paths, allowing you to maintain your desired folder structure.

That’s it! You now have two solutions to prevent WebStorm from automatically editing relative imports of files from the same folder. Choose the solution that best fits your needs and coding style.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *