Import a CSS file from node_modules in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# Import a CSS file from node_modules in React

Use an absolute path to import a CSS file from node_modules in React.

Make sure you have the specific package installed, omit the node_modules directory and start with the package name.

App.js
// 👇️ import CSS from node_modules import 'bootstrap/dist/css/bootstrap.min.css'; const App = () => { return ( <div> <h2 className="text-white bg-dark">hello world</h2> </div> ); }; export default App;

import css file from node modules in react

The code for this article is available on GitHub

The example imports the CSS for the bootstrap package directly from the node_modules directory.

If you are importing a CSS file from the node_modules directory into a CSS or SCSS file, prefix the path with a tilde ~, e.g. @import '~bootstrap/dist/css/bootstrap.min.css'.

The tilde ~ is used to indicate an absolute path.

When importing a CSS file from node_modules, you have to make sure you have the specific package installed, e.g. by running npm install bootstrap.

Note that you shouldn't use a relative path to import from node_modules.

You should use an absolute path and omit the node_modules directory.

Your import should start with the specific name of the package you are importing from.

Once you start typing the name of the package in the import path, e.g. bootstrap/, your IDE should be able to help you with autocomplete.

If your IDE doesn't help you with autocomplete, chances are your import path is incorrect or you haven't installed the specific package.

A general rule of thumb is that most packages have a dist directory, e.g. bootstrap/dist where the CSS files are located.

Most of the time you should be looking for files with .min.css extension, because these files have been minified to reduce their size and improve performance.

The code for this article is available on GitHub

Make sure to never start your import path with node_modules, because the directory is implied when using absolute imports with third-party packages and should not be included in the path.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.