What are node_modules in React?

What are node_modules in React?

ยท

2 min read

When creating a new React app your project will be populated with a bunch of new folders and files, and you may have noticed a node_modules folder that contains an insane amount of folders.

If you're nosy like me you may have wondered what is this node_modules folder, and what is its purpose? Well wonder no more!

What are node_modules?

node_modules are one of the most important directories in your React project as React requires node_modules to run. The node_modules directory is where all the dependancies packages are stored that are used to build and run your react project.

So this is you'll find packages like React and React-DOM, your build packages like Vite, Babal or Webpack, and linters like ESLint or Prettier to name just a few. This directory can contain hundreds of dependancies!

Why aren't they included in version control?

So if node_modules is such a crucial directory for your react project, why isn't it tracked with version control and included in the project repo?

The main reason is the sheer size of this directory. Rather than including hundreds of package dependancies in version control, we can instead track a file called package.json which contains information about the project, and a list of dependencies required by the app. Other developers can use the package.json file and npm install to regenerate the node_modules.

Heaviest objects in the universe - node modules

๐Ÿ˜ฑ I've accidentally tracked node_modules

Best practice would be to include the node_modules in the .gitignore file in your project before pushing any code, which will prevent version control from tracking this folder - but if you've accidentally tracked and pushed the node_modules to GitHub, like I did in my first project ๐Ÿคฆ๐Ÿปโ€โ™€๏ธ, simply follow the steps below.

Remove node_modules from version control

  1. Create a .gitignore file in your project and add node_modules

  2. Remove the node_modules:

      git rm -r --cached node_modules
    
  3. Commit and push without the node_modules. The node_modules should now be deleted from your repository.

ย