Snowpack - Dev Server - Compile Css on Server Start

01/22/2022, Sat
Categories: #shell #JavaScript #css
Tags: #NodeJs

Linaria CLI

CSS-in-Js styles are quite modular given their ability to be associated with components, but it is also helpful to have the option to compile some styles ahead of time for a html page to use. This behavior is desired if there are common global styles that referenced by all pages. Having minimum styles on the page in a css file also helps to prevent the flash of unstyled content.

In the following example, Linaria will be shown as the CSS-in-Js of choice since this library supports compilation during build.

Create a new project and install the project dependencies:

npm install snowpack @snowpack/plugin-run-script @linaria/cli @linaria/shaker

For this example, the build folder will reside in the content folder. Create a gitignore rule to ignore the build folder.

Configure the "snowpack" config file to use the "@snowpack/plugin-run-script" to run the build of the conversion of js styles to css styles file.

// snowpack.config.js
module.exports = {
  mount: {
    "content": { url: '/' }
  },
  plugins: [
    [
      "@snowpack/plugin-run-script",
      {
        "cmd": "npx linaria -o 'content/build/' -r './content/' './content/styles/project.js'",
        "watch": "npx linaria -o 'content/build/' -r './content/' './content/styles/project.js'"
      }
    ]
  ]
};

Create the main "index.html" for displaying the sample styles content and "project.js" for the global page styles. The "project.js" will have the Linaria CSS-in-Js content which will output a "project.css" which the "index.html" will refer to.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./build/styles/project.css">
</head>
<body>
  Some content.
</body>
</html>

Add a general gray background color for all pages.

// project.js
import { css } from '@linaria/core';

export const globals = css`
  :global() {
    html {
      background-color: gray;
      color: white;
    }
  }
`;

Start the snowpack dev and the "project.css" file will be generated.

snowpack dev

The project file structure should look like this after setup and compilation:

├── content
│   ├── build
│   │   └── styles
│   │       └── project.css
│   ├── index.html
│   └── styles
│       └── project.js
├── package.json
├── package-lock.json
└── snowpack.config.js