Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove/unimport inline CSS with Webpack?

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.

like image 990
Damian Pavlica Avatar asked Nov 09 '22 09:11

Damian Pavlica


1 Answers

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

like image 101
Tarnay Kálmán Avatar answered Dec 15 '22 17:12

Tarnay Kálmán