I am working on a website where I need to toggle between dark mode and light mode. Both mode uses different CSS files from node_modules (from a package). Now, how can we dynamically import and use CSS files from node_modules?
Regular import import cssfile from 'package-name/path/to/cssfile'
works however, assigning link href to 'package-name/path/to/cssfile'
gives Not Found error.
CSS files are working when imported using import statement. But, the requirement is to import the files based on toggle.
2
Answers
You cannot proceed that way as node_modules package are not accessible directly on runtime.
On your project, you have to declare 2 css such like "dark.css" and "light.css"
On
dark.css
you can used @import (or whatever you want depending if you are on sass, less, etc.) to import css from node_modules :@import '~package-name/path/to/cssfile_dark'
You have to do the same for light.css
That way, when building your project, you will have 2 CSS generated (check your conf to add them both), dark.css and light.css will be accessible on runtime, meaning using href link.
Best,
EL
I think this is not an issue with loading css dynamically.
For a fundamental solution, dark mode must be applied in a different way.
<link />
tag dynamically (not recommended, what you tried).<html>
or<body>
.