How to Import and Bundle CSS-files Using @import in Sapper

Mostly for my own bad memory, here is a simple way to import CSS files in Sapper, and make it part of your bundle in production using svelte-preprocess and postcss.

Post meta:

Install Dependencies

To import CSS-files in Svelte-components we will use svelte-preprocess with postcss and postcss-import.

npm install postcss postcss-import svelte-preprocess --save-dev

rollup.config.js

In rollup.config.js we will setup svelte-preprocess in the simplest way possible…

import sveltePreprocess from 'svelte-preprocess';

Then define a preprocess constant:

const preprocess = sveltePreprocess({
    sourceMap: dev,
    postcss: {
        plugins: [require('postcss-import')()]
    }
});

We will add preprocess to both svelte calls in the exported object’s plugins property (Sapper 0.29.1):

export default {
    client: {
        /* ... */
        plugins: [
            /* ... */
            svelte({
                /* ... */
                preprocess,
            }),
            /* ... */
        ],
        /* ... */
    },
    server: {
        /* ... */
        plugins: [
            /* ... */
            svelte({
                /* ... */
                preprocess,
            }),
            /* ... */
        ],
        /* ... */
    },
    /* ... */
};

Import CSS Files

We can use a CSS library from NPM:

npm install floor-typography-css --save-dev

Then we import it somehow (Floor Typography CSS v. 19):

<style global>
@import 'floor-typography-css/src/reset.css';
@import 'floor-typography-css/src/normalize-style.css';
@import 'floor-typography-css/src/vars.css';
/* Files below are optional: */
@import 'floor-typography-css/src/headings-font.css';
@import 'floor-typography-css/src/headings-font-lg.css' (min-width: 1200px);
/* Or: @import 'floor-typography-css/src/headings-font-w1200px.css'; */
@import 'floor-typography-css/src/headings-margin.css';
</style>