Article
3 comments

How to use Bootstrap in SharePoint Framework projects

Many developers in the past have use Frameworks such as Bootstrap or Zurb’s Foundation, and from a pure developer perspective, it is clear why to use them. There is yet Office UI Fabric around, but with every new framework, you need to learn those frameworks specifics.

Because it is and was so famous for the use of SharePoint web parts you might like to update some of your existing web parts to the modern experience. Whatever the reason is might by you use it; there are some things to know before such framework can be embedded safely in SharePoint Framework projects.

Do not use bootstrap from CDN

Using Bootstrap via a CDN URL is tempting. The problem with this approach is that it gets registered on the page level. I the case another web part uses bootstrap too but a different version it might cause troubles and break the user experience. Not only on the web parts but maybe the overall page.

Think about the following scenarios. The first web part on the page uses Bootstrap in the version “3.3.7”, the second web part uses version “2.3.2”, and the third web part uses version “v4 Alpha 6”. Guess who wins? Not your customer or user. Those versions may be completely different, and it is most likely that you will break the user experience and functionality.

Let’s see what else you could use instead of this CDN approach.

Focus on components

To be honest, I doubt that you need the full bootstrap implementation in such a component like a web part. Be focused on only the things you need rather than take everything is always a useful guideline, from my point of view.

Customise and download your custom bootstrap

Bootstrap has an elegant solution for that anyway. It allows you to generate your own trimmed down version of the complete framework even with custom colours. You will find this under “Customise and Download” on the bootstrap web site.

In my case and for this blog post I just wanted to use the table styles in a new web part. After the configuration, I got a small zip file with all the required style definitions. The package also contains a JSON file that contains my chosen configuration. In future, you can upload that file again, customise and add new components, download the setting and styles and use it in your project.

Customised Bootstrap version for use in web part

The file size is tiny, and now we are ready to embed the table styles in a web part.

SASS is incredible on external style sheets

Now with this trimmed down CSS you can safely add these files to your web part project. Before we do this here are just some basics on how SASS deals with external CSS files.

To embed external style sheet, you can use the so-called @import declaration. Like in regular CSS those files can be imported from the file system or an URL. Here are four example of this basic use.

// local url on web server 
@import url("MyPrint.css");     
// local file
@import 'custom.css';
// remote file
@import url("https://awesome.cdn/remote.css");
// local url only for screen and orientation landscape
@import url('landscape.css') screen and (orientation:landscape);

In SASS you can use the same @import statements too. The definitions above will be treated as a regular CSS import, but you can also use the same to import so-called partial files.

These partial files are similar to partial classes in C#. Those files are easy to identify in a project because partial files always start with an underscore. This marker in the filename signals the compiler to ignore that file during the build process. Or in other words, a file with the name _partialfile.scss won’t produce a CSS file named partialfile.css. The only way to use those partial files is to @import them into a SASS file without the underscore up front. A practical example is if you have a main.scss for example then this will get compiled to a file named main.css.

Now when you import a file named _partialfile.scss in the main.scss the code then will be embedded directly to the content of the main.css. The following example shows the content of such files.

// this is the content of the file '_partialfile.scss'
a{
  color: green;
  &:hover{
    color: red;
  }
}

The content of the main.scss looks like this and contains an import statement.

// this is the content of the file 'main.scss'
body{
  background-color: yellow
}

@import 'partialfile'

You might recognise that on the import statement the partial file is named without any extension. This is because the extensions are not when you import SASS files or partial files like I did here. Both files will end up in a new main.css, and the following result shows the content of the final CSS.

// this is the content of the resulting file 'main.css'
body{
  background-color: yellow
}

// this is the content of the file '_partialfile.scss'
a{
  color: green;
}
a:hover{
  color: red;
}

So there is no strict rule that every partial file need to start with an underscore. The merge of both files happen even when the data to import is stored in a file named partialfile.scss. The real benefit here is not to compile files that you don’t need. From my perspective, this is the real superpower of SASS, because it allows you to structure your CSS better and each component gets its own files in my projects. Done with the basics, let’s import our tiny part of Bootstrap in a SharePoint Framework project.

Combine SPFx with our little custom bootstrap styles

At the beginning of this post, I downloaded a small piece of bootstrap. Now it is time to use these style definition in a project.

New SPFx Project to test run Bootstrap

Create a new web part project. Then select the needed files and copy the CSS files, bootstrap.css andbootstrap-theme.css next to your web part code.

Copy Bootstrap Files for use in the project

In this case I selected not the minified version because of this a task done by the SharePoint Framework project.

bootstrap.css and bootstrap-theme.css in the source folder of the web part

The next step is to convert those to partial SASS files. This can be done merely by renaming the file names of both files.

CSS files converted to partial SASS files

The files now should have the name _bootstrap.scssinstead of bootstrap.css and _bootstrap-theme.scss instead of bootstrap-theme.css. You can rename these files to anything you want as long as you change the file extension and add an underscore before the file name. As mentioned early, partial files will not be converted into CSS files.

To make use of those partials, we need to import both files into the main style sheet file. In my case this is name BoostrapStylesWebPart.module.scss. After removing the default styles, the code looks like this.

// This is the web part container
.boostrapStyles {

  @import 'bootstrap';        // base of bootstrap 
  @import 'bootstrap-theme'; // our component for the web part

}

The style sheet class is my outer container div element of the web part. You might recognise that I imported the partial files directly inside instead of import everything on the top level. The reason for this I want to make sure all the elements affect my web part and not the page.

In fact, there is a styled body element in the partial bootstrap file, through the import inside this class all styles specified in the partials will get automatically prefix with the web part class.

So, the body{ .... } definition will become .bootstrapStyles body{ .... }. Now the body is unable to affect the overall page design. Yes, you can remove those unwanted elements, but this needs to be done everytime you update the styles you downloaded from the bootstrap web site. It this is not really practical.

In case of the body style definition it doesn’t make real sense to have it, but besides, this file also contains specific CSS reset information for table elements, headlines and many other base HTML elements too. Those reset declarations are required for bootstrap, but only in the scope of the web part, not the overall page.

Right now with the code provided above everything should work well, but if you take a look at the style object the web part uses you see the following result cause be CSS Modules.

Style object affected by CSS-Modules and Bootstrap

If you do not like to replace all the bootstrap class names with the equivalent property of the style object, there is again an old trick for that. Wrap it in the infamous CSS modules :global pseudo-class.

// This is the web part container
.boostrapStyles {

  :global{
    @import 'bootstrap';        // base of bootstrap 
    @import 'bootstrap-theme'; // our component for the web part
  }

}

This slightly modified code avoid that CSS Modules kicks in and replaces all the class names. Instead, it gives the benefit that all bootstrap classes can be used directly in the web part code. Lets put this on trial and fetch some code from the bootstrap documentation.


  public render(): void {
    this.domElement.innerHTML = `
      <div class="${ styles.boostrapStyles}">
      <table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First Name</th>
      <th scope="col">Last Name</th>
      <th scope="col">Username</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
      </div>`;
  }

I added the HTML markup of the table directly inside the render method of the web part. Finally, I added the web part to the page the result can be seen in the next screenshot.

Striped Bootstrap Table Style in an SPFx Web Part

In this case, I choose the striped table layout. If you want to change the table layout to be non-striped the only thing to change is the class name from table table-striped to table on the table HTML element.

Unstriped Bootstrap Table Style on an SPFx web part

Again, the table now shows the corresponding design.

What else?

In this blog post, you learned some of the SASS basics and how Bootstrap safely can be used in SharePoint Framework web parts. There are some key takeaways that you should keep in mind.

Instead of using the complete framework you should precisely choose only the components required for your web part. This way the overall bundle only contains the needed ingredients, and the size is smaller than including the complete framework. I also showed you how to make a safer use of bootstrap through the right scoping to the web part and not the overall page experience.

Last but not least through the help of the :global pseudo-element you still can use all style sheet classes defined on the Bootstrap documentation rather than CSS Modules compiled style object. I hope this small tricks and components help you a lot when you like to migrate existing web part to the modern experience.

3 Comments

      • I get this error ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src??postcss!./lib/webparts/test/testWebPart.module.css)
        Module not found: Error: Can’t resolve ‘../fonts/glyphicons-halflings-regular.woff’

        Field ‘browser’ doesn’t contain a valid alias configuration.

        I can share my github repo if you want to take a look

        Reply

Leave a Reply

Required fields are marked *.


This site uses Akismet to reduce spam. Learn how your comment data is processed.