Search code examples
javascriptnpmnode-modulescreate-react-app

Can I review which node_modules I need?


Is there a way to review which node_modules packages are used in my create-react-app project and delete modules which are not in use? Other than manually reviewing all used packages and their dependencies?

I'd like to reduce the amount of space used up by the project. It's committed to a resources repository, and the node_modules folder alone triples the space used.


Solution

  • For repo size (assuming you're using git):

    1. git rm -r --cached ./node_modules
    2. Add the line /node_modules to your .gitignore file
    3. git add .
    4. git commit -m "Remove node_modules from repo"

    For build size:

    create-react-app is pretty good at tree shaking, so you shouldn't need to worry too much about this. Certain packages may have more modular ways of importing, which can help - usually these will be documented on a package-by-package basis. For example, Material UI icons supports two import syntaxes:

    // option 1
    import AccessAlarmIcon from '@material-ui/icons/AccessAlarm'
    import ThreeDRotation from '@material-ui/icons/ThreeDRotation'
    // option 2
    import { AccessAlarm, ThreeDRotation } from '@material-ui/icons'
    

    Of these, option 1 is likely to yield the smallest bundle size.

    For size on your development machine:

    The biggest difference you can make here (assuming you have other projects) is probably switching to something like pnpm, which stores node_modules centrally on your local machine and then links out to them from your project, rather than having many instances of identical modules.

    For general housekeeping and tidiness:

    You could try using a tool such as depcheck to detect unused dependencies. This is probably overkill, though, unless it's a particular pain point for your project.