Friday, 24 January 2020

Inject per-component style tags dynamically with Rollup and scss

I am building a React component library whose source code takes this general structure:

- src
  - common.scss (contains things like re-usable css variables)
  - components
    - button
      - index.js
      - button.scss
    - dialog
      - index.js
      - dialog.scss

My components are responsible for importing their own per-component styles (using scss), so for example, button/index.js has this line:

import "./button.scss";

So far, in my application I have been consuming my library directly from source like this:

// app.js
import "mylib/src/common.scss" // load global styles
import Button from 'mylib/src/components/button/index.js'
import Dialog from 'mylib/src/components/dialog/index.js'

// ...application code...

When my application uses webpack, along with style-loader, the per-component css is appended as style tags in head dynamically when the component is first used. This is a nice performance win since the per-component styling doesn't need to be parsed by the browser until it's actually needed.

Now though, I want to distribute my library using Rollup, so application consumers would do something like this:

import { Button, Dialog } from 'mylib'
import "mylib/common.css" // load global styles

// ...application code...

When I use rollup-plugin-scss it just bundles the per-component styles all together, not dynamically adding them as before.

Is there a technique I can incorporate into my Rollup build so that my per-component styles are dynamically added as style tags in the head tag as they are used?



from Inject per-component style tags dynamically with Rollup and scss

No comments:

Post a Comment