webpack-contrib / style-loader

Style Loader
MIT License
1.65k stars 473 forks source link

Get CSS properties / variables from JavaScript #602

Closed imabot2 closed 1 year ago

imabot2 commented 1 year ago

Feature Proposal

I would like to get the CSS variables or properties from CSS files even if there are unused.

Feature Use Case

I use this plugin to change pages theme dynamically. The user pick a theme and it is apply to the page thank to lazy loading (use() / unuse())

It works fine, but I would like to display a preview of the theme before applying it. Is there a way to read the CSS variables or properties from JavaScript? Or, to apply the style inline to an element?

I already had a look at the object returned by: import themeDark from './assets/themes/dark.css'; There are the two functions use() / unuse() and an object, maybe it is in the object?

As we have themeDark.use(), is would be great to get a themeDark.getVariable ('main-color') for example. If it is not possible right now, maybe a future feature?

Please paste the results of npx webpack-cli info here, and mention other relevant information

  System:
    OS: Linux 5.19 Ubuntu 22.04.2 LTS 22.04.2 LTS (Jammy Jellyfish)
    CPU: (4) x64 Intel(R) Core(TM) i5-4570 CPU @ 3.20GHz
    Memory: 23.83 GB / 31.24 GB
  Binaries:
    Node: 18.16.0 - ~/.volta/tools/image/node/18.16.0/bin/node
    npm: 9.5.1 - ~/.volta/tools/image/npm/9.5.1/bin/npm
  Browsers:
    Chrome: 112.0.5615.121
  Packages:
    css-loader: ^6.7.3 => 6.7.3 
    html-webpack-plugin: ^5.5.1 => 5.5.1 
    style-loader: ^3.3.2 => 3.3.2 
    webpack: ^5.82.0 => 5.82.0 
    webpack-cli: ^5.0.2 => 5.0.2 
alexander-akait commented 1 year ago

We don't handle CSS variables, so you can use pure JS to get them

imabot2 commented 1 year ago

@alexander-akait When we use lazySingletonStyleTag or lazyStyleTag, the CSS is necessarily loaded in RAM until you apply the style with.use(). As variables are part of CSS, you handle CSS variables in one way or another.

What I need is to access the CSS from the JavaScript even if the CSS is unused (i.e. not yet apply with .use()).

If it is already possible, I didn't find how to do this in the docs.

alexander-akait commented 1 year ago

Sorry, it is impossible using just style-loader, you can move your variables to JSON file then, for example use postcss or sass or less, to inject your CSS variable values into CSS and import this file where you need, sorry it is out of scope style-loader, we don't look at content of CSS files, we are working with your DOM