skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. I think this is not an issue with loading css dynamically.

    For a fundamental solution, dark mode must be applied in a different way.

    • Option 1: Toggle <link /> tag dynamically (not recommended, what you tried).
      • Not recommended because of potential issue with style conflict or delayed styles.
      • To do this, you must first copy the CSS from node_modules to the public directory or follow Errol Lebron‘s way (may require build settings for it).
    • Option 2: Toggle classes or attributes for identify dark mode on tags such as <html> or <body>.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search