Search code examples
bootstrap-4sveltesvelte-3

How to setup global bootstrap via scss in Svelte?


I want to use Bootstrap (v4.5) in a Svelte (v3) project with custom theme.

The bootstrap documentation states that you can do this with scss. So I've setup Svelte with svelte-preprocess as follows:

Added to my package.json:

    "bootstrap": "^4.5.2",
    "node-sass": "^4.14.1",
    "svelte-preprocess": "^4.0.10",

In my rollup.config.js:

...
import preprocess from "svelte-preprocess";

export default {
  ...,
  plugins: [
    ...,
    svelte({
      // enable run-time checks when not in production
      dev: !production,
      // we'll extract any component CSS out into
      // a separate file - better for performance
      css: (css) => {
        css.write("public/build/bundle.css");
      },
      preprocess: preprocess(),
    }),

In my App component:

<style type="text/scss" global>
  // Variable overrides for bootstrap
  $primary: #19197c;
  $secondary: #fd6400;
  $light: #d8d8d8;

  @import "../node_modules/bootstrap/scss/bootstrap";

</style>

Unfortunately, it looks like Svelte purges all the styles since I don't get bootstrap styling in my application. I would like to use bootstrap normalization as well as bootstrap classes. Any tips? Thanks!


Solution

  • I figured out how to get this working. You have to separately process the sass outside of Svelte, using rollup-plugin-scss, so that the classes are not purged.

    In rollup.config.js:

    ...
    import scss from "rollup-plugin-scss";
    
    export default {
      ...,
      plugins: [
        ...,
        svelte({
          // enable run-time checks when not in production
          dev: !production,
          emitCss: true
        }),
        scss(),
        ...,
    

    Create a new file called main.scss:

    // Variable overrides for bootstrap
    $primary: #19197c;
    $secondary: #fd6400;
    $light: #d8d8d8;
    
    @import "../node_modules/bootstrap/scss/bootstrap";
    

    In main.js:

    import "./main.scss";
    import App from "./App.svelte";
    
    const app = new App({
      target: document.body,
      props: {},
    });
    
    export default app;
    

    That's it!