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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With