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:
- Open the WebStorm settings by going to File > Settings (or WebStorm > Preferences on macOS).
- Navigate to Editor > Code Style > TypeScript.
- Click on the “Imports” tab.
- Uncheck the “Use path mapping” option.
- 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:
- Create a
tsconfig.json
file in the root of your project if you don’t already have one. - 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!
Leave a Reply