Borislav Hadzhiev
Last updated: Apr 19, 2022
Photo from Unsplash
Use an absolute path to import a CSS file from node_modules in React, e.g.
import 'bootstrap/dist/css/bootstrap.min.css'
. Make sure you have the specific
package installed, omit the node_modules
directory and start with the package
name.
// 👇️ 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;
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.
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.
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 size and improve performance.
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.