Add external CSS or styles to SPFX solution
When I started to work with SPFX solutions for SharePoint, I couldn’t understand how to load external CSS files. I came up with one solution, but it was a crutch. I did it with embedding <styles> tag into JSX. It looked like this:
<div>
<style>{`
.mbsc-timeline-header-week-text {
width: auto;
text-align: center; margin: 1px; padding: 1px;
font-size: 10px;
}
.mbsc-timeline-header-column, .mbsc-timeline-column {
width: auto; min-width: 34px;
}
`}
</style>
….
</div>
There’s a good way to load external CSS into SPFX webparts with SPComponentLoader. It allows you to load css from assets directory of your solution, float SharePoint document library or from any external site (CDN, for example).
import { SPComponentLoader } from '@microsoft/sp-loader';
....
// and modify onInit method with loading CSS
protected onInit(): Promise<void> {
return this._getEnvironmentMessage().then(message => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cssYet = require('./assets/styles.css')
SPComponentLoader.loadCss(cssYet)
//SPComponentLoader.loadCss(this.context.pageContext.web.serverRelativeUrl + '/SiteAssets/yet-another-react-lightbox-styles.css');
this._environmentMessage = message;
});
}
UPD 09 April 2024 for SharePoint On-Premises 2019
If you work with a solution for SharePoint On-Premises 2019 and SharePoint Online, there's a small difference. I won't tell, that you need Node v8.17.0 and React 15 - it won't make you optimistic. Here's the way how to add external CSS to a SPFX solution.
1. add directory 'assets' in the directory of your webpart.
2. in the root .tsx file in the 'render(): void' method add the code:
require('./assets/eurostyles.css')
That's all 🙂 You don't even need to add SPComponentLoader like for modern SharePoint online solutions and it will work.