Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Documentation about global styles #377

Closed
arggh opened this issue Aug 24, 2018 · 15 comments
Closed

Documentation about global styles #377

arggh opened this issue Aug 24, 2018 · 15 comments

Comments

@arggh
Copy link

arggh commented Aug 24, 2018

Currently there's not a single word about global styles in the docs.

However, in the Sapper starter app there is a file named global.css in the assets folder with some basic reset CSS, so I'm assuming the current preferred way is to just drop the file in the folder and be done with it.

This could be improved (#357) or at least documented.

@Crisfole
Copy link

I think that this is because it's not Sapper specific: global.css is just a css file. The sapper-template project includes it in <head> in template.html as a convenient place to stick global styles; otherwise it's literally no different from the css file you loaded in <head> when you ran through your very first 'Learn CSS' tutorial.

@arggh
Copy link
Author

arggh commented Aug 27, 2018

@Crisfole sure, but I think it might be worth a tiny mention in the docs. I'd be even happier, if I could just drop a css, scss or less file into the project and it would be processed with the configured preprocessor pipeline just like Svelte components!

@kylecordes
Copy link

It would be great to see Sass/Postcss/Less/whatever end up with "official" support in Sapper, in the box rather than something that you can discover how to add yourself; and even better that it would also process global files. (The fewer the ad hoc per project settings needed, the easier it is to keep up with progress in the underlying platform. Complex, subtle, bespoke, artisanal webpack configuration can be a source of technical challenge and joy, but it is a financial tar pit.)

@blindfish3
Copy link

@kylecordes - I had a similar issue with the Svelte starter template: it looks like the workaround I used there can work in the Sapper template (though I've no idea if this is the Right Way™ to do this). I'll document it here in case it's useful to anyone - or someone can point me to a better approach ;). If using Rollup:

  • add src/styles/global.scss as your source file

  • in rollup.config.js add the following to client config (I guess you have to add to server too):

      sass({
          output: "static/global.css"
        }),
    
  • in src/client.js add import "./styles/global.scss"; (again I guess this will be required in server for it to work there)

  • src/template.html should already have a line to load the global stylesheet:
    <link rel="stylesheet" href="global.css" />

I'm still feeling my way around Rollup; but I think the import in client.js triggers the appropriate processor for that file; and this is configured to output the file to /static. I only just tested this; so not sure yet how to get it to automatically reload on change...

Hopefully didn't miss anything - I'll double-check later.

@Bandit
Copy link

Bandit commented Nov 29, 2019

@blindfish3 sorry to necro this, but what do you import in order to add sass({ ... }) to rollup.config.js? There are so many Sass related packages I'm a bit lost.

@blindfish3
Copy link

@Bandit - no worries. I have the following in my current rollup.config.js (I've removed a lot that's not relevant):

// this is for preprocessing sass in .svelte files
import { sass as sv_sass } from "svelte-preprocess-sass";

// this is what you want for globals.css:
import sass from "rollup-plugin-sass";

export default {
  client: {
  input: config.client.input(),
  output: config.client.output(),
  plugins: [
  // ...
    sass({
     // update includePaths to what suits.
    // node_modules is probably only necessary if you need to import from a css library
      includePaths: ["./src/styles", "node_modules"],
      output: "static/global.css"
    }),
    svelte({
      dev,
      hydratable: true,
      emitCss: true,
      preprocess: {
        style: sv_sass({
              includePaths: ["./src/styles", "node_modules"],
            })
        }}),
  // ...
  ]

Note that in .svelte files you need to declare that you want sass by adding an attribute to the style tag:

<style type="text/sass">

Both globals and .svelte preprocessing works for me; though I haven't seen the most recent version of the sapper template so things may have changed...

@timoanttila
Copy link

For unknown reason, Svelte / Sapper removes part of my needed CSS from global.css. Everything outside of _layout.svelte, ex. reset (using *) and styles for html, body and div#svelte. Everything is valid CSS.

@Crisfole
Copy link

@tewdin that seems like a bug report. You'll definitely want to report it here.

It'd be super helpful if you posted a copy of the global.css as it exists in your directory and as you're seeing it in the browser's Network tab (in the developer console).

@Sidd27
Copy link

Sidd27 commented Feb 22, 2020

@Bandit - no worries. I have the following in my current rollup.config.js (I've removed a lot that's not relevant):

// this is for preprocessing sass in .svelte files
import { sass as sv_sass } from "svelte-preprocess-sass";

// this is what you want for globals.css:
import sass from "rollup-plugin-sass";

export default {
  client: {
  input: config.client.input(),
  output: config.client.output(),
  plugins: [
  // ...
    sass({
     // update includePaths to what suits.
    // node_modules is probably only necessary if you need to import from a css library
      includePaths: ["./src/styles", "node_modules"],
      output: "static/global.css"
    }),
    svelte({
      dev,
      hydratable: true,
      emitCss: true,
      preprocess: {
        style: sv_sass({
              includePaths: ["./src/styles", "node_modules"],
            })
        }}),
  // ...
  ]

Note that in .svelte files you need to declare that you want sass by adding an attribute to the style tag:

<style type="text/sass">

Both globals and .svelte preprocessing works for me; though I haven't seen the most recent version of the sapper template so things may have changed...

I have Tried your way global.css is not getting genrated

@blindfish3
Copy link

blindfish3 commented Feb 26, 2020

@Sidd27

I have Tried your way global.css is not getting genrated

It works for me with the latest version of the sapper template. If you took my quoted post in isolation you probably missed the instructions in my earlier post - especially:

in src/client.js add import "./styles/global.scss";

One thing worth noting: live-refresh isn't working on changes to global.scss: I have to hard refresh the browser. I didn't look into this further as I can't imagine making frequent changes to global css.

@siebeneicher
Copy link

@blindfish3 way works well! thanks dude

@gavinmcfarland
Copy link

gavinmcfarland commented Jun 22, 2020

I wanted a convenient way to get PostCSS working with global.css so I wrote the following which parses the CSS and watches for changes. It uses postcss-load-config so you can specify plugins using postcss.config.js.

// preprocessPostCSS.js
const fs = require('fs');
const postcss = require('postcss');
const postcssrc = require('postcss-load-config');
const chokidar = require('chokidar');
const path = require('path');

const ctx = { parser: true, map: 'inline' };

export default function processPostCSS(input, output) {
	var dir = path.dirname(input);
	chokidar.watch(input).on('all', (event, path) => {
		fs.readFile(input, (err, css) => {
			postcssrc(ctx).then(({ plugins, options }) => {
				postcss(plugins).process(css, { from: input, to: output }).then((result) => {
					fs.writeFile(output, result.css, () => true);
					if (result.map) {
						fs.writeFile(output + '.map', result.map, () => true);
					}
				});
			});
		});
	});
}

Then in your Sapper Rollup config import and call the function.

// rollup.config.js
import processPostCSS from './preprocessPostCSS;

// ...

// processPostCSS(input, output)
processPostCSS('src/styles/index.css', 'static/global.css');

Technically it doesn't have to be inside the rollup config. It could be in a separate file.

To enable hot reloading, add the following inside your Rollup config as well and change the directory to watch.

// rollup.config.js
import glob from 'glob`;

export default {
    server: {
        plugins: [
            {
                buildStart() {
                    var self = this;
                    var dir = 'src/styles/'
                    glob(dir + '**/*', null, function (er, files) {
                        files.forEach((file) => {
                            self.addWatchFile(file);
                        });
                    });
                }
            }
            // ...
        ]
    }
}

Remember to add a postcss.config.js file with the plugins you need and install them as dev dependencies.

// postcss.config.js

module.exports = {
	plugins: {
		'postcss-import': {}
	}
};

@shelby-carter
Copy link

shelby-carter commented Aug 25, 2020

You can do that quite simple by using svelte-preprocess
https://github.com/sveltejs/svelte-preprocess

The following example also utilizes SASS styles.

In your rollup.config.js

import sveltePreprocess from 'svelte-preprocess';

const preprocess = sveltePreprocess({
  postcss: true,
  sass: true
});

So apart from SASS we're enabling postcss

And just use that variable in plugins section

plugins: [
    svelte({
        dev: !production,
        preprocess, // Make sure to add it before the `css: css => {` line, otherwise you might have funny issues in compiled css
        css: css => {
            css.write('public/build/bundle.css');
        }
    }),
    bla bla bla
]

Then anywhere where you want to use global styles just wrap styles in :global{ ... }
In my case it's just importing other file as global styles

<style lang="scss">
    :global{
        @import '../../../node_modules/bootstrap-4-grid/scss/grid.scss';
        @import '../../sass/styles.scss';
    }
</style>

Or just add global property to <style> tag

<style global lang="scss">
    @import '../../../node_modules/bootstrap-4-grid/scss/grid.scss';
    @import '../../sass/styles.scss';
</style>

@riccardolardi
Copy link
Contributor

riccardolardi commented Aug 30, 2020

Any caveats when using <style global lang="scss">... in special routes like _layout.svelte? I was trying to declare some styles in _layout.svelte so I can use them later down the tree but wasn't able.

Also, this errors out for me with [!] (plugin svelte) ParseError: :global() must contain a selector:

<style lang="scss">
    :global{
        @import '../../../node_modules/bootstrap-4-grid/scss/grid.scss';
        @import '../../sass/styles.scss';
    }
</style>

@antony antony added the stale label Oct 30, 2020
@antony antony closed this as completed Oct 30, 2020
@samal-rasmussen
Copy link

samal-rasmussen commented Nov 1, 2020

I'm getting the same ParseError: :global() must contain a selector on the same snipped as riccardolardi.

EDIT: I was missing postcss. npm i postcss fixed it. Reading the svelte-preprocess getting started guide cleared this up for me: https://github.com/sveltejs/svelte-preprocess/blob/HEAD/docs/getting-started.md

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests