Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refactor by moving files in a JavaScript project and have references update automatically?

General tips are welcome. My specific situation is a React app, compiled with WebPack, with lots of files. If I want to move a file or folder within the project, is there a good way to do this such that references, such as import & require statements, update automatically?

Bonus points for solutions using Atom or VSCode.

NPM scripts will also work. Thanks.

like image 586
Alan H. Avatar asked Sep 08 '20 06:09

Alan H.


1 Answers

I used a few text editors with plugins and IDE's during the years, this includes Atom, VSCode, SublimeText, etc. but keep coming back to Jetbrains products and one of the reason is the refactoring capabilities.

Jetbrains dedicated JavaScript IDE, Webstorm does it very well without any additional plugins or hacks.

All you need to do is drag and drop your file or folder to another location and all the relevant imports will be updated (make sure search for references is ticked in the confirmation pop up). This applies to both es6 import and/or common js require().

This is not all, you can rename variables, class, function names, whatever you like, just make sure you doing it by selecting the text, then right click then refactor and rename (you'll see in this menu you can do much more if you want)

Whenever you about to confirm your changes you can select the option in the pop-up that is "search in comments and strings" if you want which is really cool as you can keep your documentation up to date as well.

This official documentation goes more in deep, but generally if you do the above, it will be enough.

I guess if you don't feel confident enough, start up the server, with (create-react-app it will reload every time you make a change as hot reloading is built in) and if something goes wrong with your refactoring you will know it straight away.

Just fyi I am not associated with Jetbrains, I just like the product. Webstorm is not free (however it's very cheap) - go for the 30 day trial version if you don't wish to pay.

UPDATE:

Also note, this feature support both relative and absolute paths as well as any file extensions, so including .*scss etc.

like image 168
anddak Avatar answered Nov 08 '22 19:11

anddak