What is the best way to use external CSS in the SPfx solution?

Toriyama 281 Reputation points
2022-05-13T09:53:55.26+00:00

In the project we have local CSS, but it would be nice to use an existing CSS on a website.
What's the best way to use this?

I know I can use it by adding the line below in the html.
<link rel="stylesheet" type="text/css" href="/sites/site/Documents/file.css" />

This works, but I don't know if it's the best.

Another way would be:
SPComponentLoader.loadCss("/sites/site/Documents/file.css");

This second way I haven't tried it yet, but it might be good.

What do you say?

Thanks

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,411 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,616 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,565 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tong Zhang_MSFT 9,116 Reputation points
    2022-05-16T06:23:04.517+00:00

    Hi @Toriyama ,

    Based on my research, you can follow these code to add external CSS Reference in SPFX Solution:

    1. import SPComponentLoader: import { SPComponentLoader } from '@microsoft/sp-loader';
    2. Add the code in onInit() method : SPComponentLoader.loadCss('https://xxx/xxx.css');
    3. Confirm that the project is building by running gulp serve

    More information for reference:
    https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/reference-third-party-css-styles#reference-third-party-css-stylesheets-from-url-in-the-web-part


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. sadomovalex 3,626 Reputation points
    2022-05-13T15:32:05.653+00:00

    as far as I understood you need to load this external css dynamically. If yes check the following post: Dynamically Load a Stylesheet with React.

    0 comments No comments