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.

5
  • What's the purpose? Are you trying to replicate HMR functionality of Webpack dev server/middleware? Commented Sep 9, 2016 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. Commented Sep 9, 2016 at 10:12
  • 1
    @DamjanPavlica In that case you might not want a generic style-loader. You could use css-loader and put a <style> tag inside your view. Commented Sep 9, 2016 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 to make them inline styles (Angular 2 also uses shadow DOM to isolate view/component style). Commented Sep 9, 2016 at 10:25
  • psst, meta.stackoverflow.com/questions/334859/… Commented Sep 19, 2016 at 16:46

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.