Using Bootstrap with Stencil Component

I’ve attempted this recently and found some success using Stencil with the @stencil/sass plugin, and importing Bootstrap’s SCSS from source as needed. I haven’t found any decent resources on this, so I experimented.

I first made a src/scss/_global.scss file in my project that looks like this:

// Bootstrap globals
@import '../../node_modules/bootstrap/scss/_functions.scss';
@import '../../node_modules/bootstrap/scss/_variables.scss';
@import '../../node_modules/bootstrap/scss/_mixins.scss';

Then in the Stencil config I’ve ensured that these Bootstrap functions, variables and mixins are available to all of my Stencil components, using the Sass plugin:

stencil.config.ts:

export const config: Config = {
  // ...
  plugins: [
    sass({
      injectGlobalPaths: [
        'src/scss/_global.scss'
      ]
    })
  ],
  // ...
};

Fortunately, by themselves, these don’t add any actual CSS to the component output. They’re just tools we can use from within our components’ .scss stylesheets.

After that, depending on the web component I’m building, I might include some specific Bootstrap component .scss file. For example, if I was making a button component that just wanted to use Bootstrap’s button styles:

src/components/my-button/my-button.scss:

@import '../../../node_modules/bootstrap/scss/_buttons.scss';

// Custom styling can go here

Refer to the Bootstrap source code for more .scss files that you can include.

This is the best way I’ve found so far to import Bootstrap styles from their SCSS source code within Stencil components in a modular fashion, all without sacrificing the use of the Shadow DOM in the resulting web components.

Hope this helps!

3 Likes