1

I'm working on a web application which currently uses bootstrap for its front end, and webpack to bundle its assets. I've been inspired by this article to create web components which can be broken into tiny little self contained units, and this article to attempt to make my use of bootstrap more semantic.

The problem arises when I attempt to combine the two practices, by trying to make multiple web components, each of which extends the functionality of bootstrap. By attempting to import bootstrap into these independent components, bootstrap's style sheets end up getting duplicated several times in the final css bundle generated by webpack.

I've specifically been using bootstrap-sass so that I have access to bootstrap's individual components and variables. This way, I only have to import the functionality I need for each component. But this still doesn't solve the problem of duplicating the code, but only reduces it.

Ideally, webpack could be configured in a way such that all of these web components are extending the same copy of bootstrap, but I can't figure out how to do it.

Here is a gist I've created which demonstrates the problem. Upon running the code it generates app.css which contains bootstrap's final css duplicated twice.

How can I structure my project so that I can semantically extend bootstrap, but still separate my style sheets into independent web components?

thejonwithnoh
  • 632
  • 1
  • 8
  • 19

1 Answers1

2

I am working on a project with the same needs. Best I managed to do was this:

First, load bootstrap through bootstrap-loader. This package can load bootstrap just once into your bundled css.

Assuming you are also using css-loader, instead of importing bootstrap and using the @extend directive in every sass, you can use css composition. For instance, supose you want your div wrapper to be centered using bootstrap's class center-block. You can declare a semantic class content-wrapper and inside your component's sass you may have

    .content-wrapper{
      composes: center-block from global;
    }

The drawback with this aproach is that such compositions just work for local classes, and not for other kinds of selectors. For instance, supose you want to style a form's submit button based on bootstrap class btn-primary. None of the rules bellow will work

    input[type="submit"] {
      composes: btn-primary from global;
    }
    .my-form {
      .my-btn-submit {
        composes: btn-primary from global;
      }
    }

On the bright side, we are not the only ones looking for a way to modularly extend bootstrap. You might want to check the following questions on github. I would have linked them, but it seems I do not have enough reputation to post over two links.

adrian
  • 2,793
  • 1
  • 23
  • 26