Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create-React-App: What's the best way to include CSS from node_module directory

I'm trying to include some CSS in my create-react-app project. The CSS is from a 3rd party NPM package and therefore its in the node_modules directory.

I tried: import '/node_modules/packagename/css/styles.css';

But I get the error:

Module not found: You attempted to import /node_modules/packagename/css/styles.css which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

I would prefer to not move the CSS to src/ so it can be updated via NPM. I could symlink but as I develop on windows and deploy to linux this isn't ideal.

What's the best way from me to include the CSS?

like image 269
Sean Bannister Avatar asked Aug 13 '17 08:08

Sean Bannister


People also ask

Where do I put the CSS file in Create React app?

To add a global CSS file to your Next. js app, you need to import the file inside pages/_app. js file.

How do I import a CSS node module into React?

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.


2 Answers

Find the path of the css file

example: ./node_modules/packagename/dist/css/styles.css

Import using the path related to node_modules (anything after node_modules/ )

import 'packagename/dist/css/styles.css' 
like image 141
Afzal Hossain Avatar answered Oct 05 '22 13:10

Afzal Hossain


relative paths are unnecessary from node_modules and should not be the recommended way to include the css

all you have to do is leave off the preceding slash and node_modules directory same as importing a js package from node modules:

import 'package/css/style-to-import.css'

when using (s)css imports, use the tilde (~) to indicate an absolute import:

@import '~package/css/style-to-import.css'

like image 21
Sampson Crowley Avatar answered Oct 05 '22 15:10

Sampson Crowley