Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preprocess both the components CSS and global styles using Rollup or Webpack in Svelte Compiler?

I believe there is an option to use a preprocessor in svelte config nowadays. But I have not managed to do it successfully yet... (Guess the community could use a working example both with Rollup and Webpack).

Before I tinker even more, I was wondering if it is possible to preprocess global.css (or any 'non-component' css) using rollup / webpack config in svelte compiler as it compiles main js?

While I do like the idea of CSS being tied to the component, there are developers who rely on global styling as much as component styling, so they don't have to repeat the styles over again in each component.

No code to show, as I would have not a clue where to start?

like image 914
J. Doe Avatar asked Jun 06 '19 08:06

J. Doe


1 Answers

This is not really a Svelte-specific problematic, but here's some directions on how to do it in Svelte's template.

In order to have CSS assets processed by the bundler (e.g. Rollup, Webpack...), you'll need to import the CSS files into your JS modules, and use the appropriate bundler plugin / loader to handle these imports.

Popular plugins for this task include rollup-plugin-postcss and css-loader, for their respective bundler.

I have pushed an example of using PostCSS with Rollup on branch here (see README for installation / usage).

In essence, here are the steps that you'll need to follow to add PostCSS support to Svelte's official Rollup template...

Install rollup-plugin-postcss:

npm install --dev rollup-plugin-postcss

Add the plugin to your rollup.config.js:

import postcss from 'rollup-plugin-postcss';

export default {
  ...
  plugins: [
    svelte( ... ),
    postcss({
      extract: 'public/build/global.css',
      sourceMap: true,
      minimize: true,
    }),
  ]
}

Of course there are many ways this plugin can be configured, and that will depend on your project. What is shown here is just to make it work. See plugin the docs for all available options: https://github.com/egoist/rollup-plugin-postcss.

Update your index.html to reference the processed asset:

<!-- <link rel='stylesheet' href='/global.css'> -->
<link rel='stylesheet' href='/build/global.css'>

(You can technically keep the unprocessed global.css, if you want to.)

Finally, import your css source files in your js files:

For example, in main.js:

import './global.css';
...
new App(...)

This is needed for the CSS file to be included in the bundle. Otherwise, the bundler would have no idea that this file is used in your app (same as if you had a JS file that is imported nowhere -- and is not an entry point).

Obviously, JS would choke trying to import raw CSS. That's why a need a special plugin / loader to handle it.

Those are only the broad strokes, but I hope it can get you started.

like image 144
rixo Avatar answered Sep 19 '22 08:09

rixo