How to find dead code in a large react project?

后端 未结 8 601
执笔经年
执笔经年 2020-12-25 12:47

In order to refactor a client-side project, i\'m looking for a safe way to find (and delete) unused code.

What tools do you use to find unused/dead code in large re

8条回答
  •  佛祖请我去吃肉
    2020-12-25 13:04

    Solution:

    For node projects, run the following command in your project root:

    npx unimported
    

    If you're using flow type annotations, you need to add the --flow flag:

    npx unimported --flow
    

    Source & docs: https://github.com/smeijer/unimported

    Outcome:

    Background

    Just like the other answers, I've tried a lot of different libraries but never had real success.

    I needed to find entire files that aren't being used. Not just functions or variables. For that, I already have my linter.

    I've tried deadfile, unrequired, trucker, but all without success.

    After searching for over a year, there was one thing left to do. Write something myself.

    unimported starts at your entry point, and follows all your import/require statements. All code files that exist in your source folder, that aren't imported, are being reported.

    Note, at this moment it only scans for source files. Not for images or other assets. As those are often "imported" in other ways (through tags or via css).

    Also, it will have false positives. For example; sometimes we write scripts that are meant to simplify our development process, such as build steps. Those aren't directly imported.

    Also, sometimes we install peer dependencies and our code doesn't directly import those. Those will be reported.

    But for me, unimported is already very useful. I've removed a dozen of files from my projects. So it's definitely worth a shot.

    If you have any troubles with it, please let me know. Trough github issues, or contact me on twitter: https://twitter.com/meijer_s

提交回复
热议问题