6

Ok, I have imported a css file with Webpack style-loader and css-loader like this:

import './style.css'

And Webpack append it to my page via style tag. So far, so good. But, when the state of application change, I want to remove this particular style. Of course, I could remove it with document.querySelector('style'), but is there some natural Webpack way of doing this?

Thanks in advance.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
  • What's the purpose? Are you trying to replicate HMR functionality of Webpack dev server/middleware? – Estus Flask Sep 09 '16 at 10:07
  • Every JS view has it own style. When I change the view, style from the previous view remains appended in the HTML. – Damjan Pavlica Sep 09 '16 at 10:12
  • 1
    @DamjanPavlica In that case you might not want a generic style-loader. You could use `css-loader` and put a ` – CodingIntrigue Sep 09 '16 at 10:20
  • 1
    I'm not sure that it is a good idea to integrate with Webpack on that level. E.g. Angular 2 starter kit uses [to-string-loader with css-loader](https://github.com/AngularClass/angular2-webpack-starter/blob/master/config/webpack.common.js#L153-L160) to make them inline styles (Angular 2 also uses shadow DOM to isolate view/component style). – Estus Flask Sep 09 '16 at 10:25
  • psst, http://meta.stackoverflow.com/questions/334859/burninate-the-game-development-tag-again –  Sep 19 '16 at 16:46

2 Answers2

2

With style-loader, you could mark some of your css files lazy, and call .use() when mounting the route, and .unuse() when unmounting the route.

React hooks example:

import styles from './styles.lazy.css';

export function LegacyRoute() {
  useLayoutEffect(() => {
    styles.use();
    return () => { styles.unuse() };
  }, []);
  return <p>Hello World</p>;
}

webpack config:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        exclude: /\.lazy\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.lazy\.css$/i,
        use: [
          { loader: 'style-loader', options: { injectType: 'lazyStyleTag' } },
          'css-loader',
        ],
      },
    ],
  },
};

Source: https://github.com/webpack-contrib/style-loader#lazystyletag

Tarnay Kálmán
  • 6,907
  • 5
  • 46
  • 57
0

Not the exact answer to this question, but if you're looking for a create-react-app solution and can't edit the webpack.config.json take a look at this answer: https://stackoverflow.com/a/67352039/5648839

arniebradfo
  • 1,141
  • 11
  • 18