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?
To add a global CSS file to your Next. js app, you need to import the file inside pages/_app. js file.
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.
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With