Emotion Css with Linaria

02/17/2022, Thu
Categories: #shell #JavaScript #css
Tags: #NodeJs

Share Global Styles on Compile and Runtime

Linaria is able to achieve zero-runtime css-in-js because it compiles the js to css before the local dev server startup, however one might wish to share and modify styles used by Linaria during development.

Since one can't use Linaria when the dev server is running for client css-in-js, the base styles will need to be handed over to another css-in-js library for modification.

To avoid redundancy in redefining the css-in-js styles that Linaria uses to a more suitable format for another css-in-js library, a shared 'global-styles.js' in css file will need to be compatible for reading by both css-in-js libraries.

Emotion css happens to be another library that can read the css in the template string format that Linaria relies on.

Create a 'global-styles.js' file which will be the base styles that will be used by both libraries:

// global.js

export default `
  html {
    background-color: gray;
  }

  body {
    width: 100%;
    max-width: 100%;
    margin: 0;
  }
`

The Linaria run definition which references the 'global-styles.js' for building before the local dev server is to start up in your package.json.

{
    ...,
    "scripts": {
        "start": "npx linaria -o 'src/build/' -r './src/' './src/styles/global-styles.js' && <your dev server start command>"
    }
}

Use Emotion to reference the 'global-styles.js' file for local development:

// index.js

// Emotion reads from the same 'global-styles.js'
// as Linaria

import { injectGlobal } from '@emotion/css'
import { default as globalStyles } from "../styles/global-styles.js";

// Global styles attached to the body
const myStyle = injectGlobal`${globalStyles}`;
document.body.classList.add(myStyle);