0

In SPFx webpart - can I import styles not from *.scss file, but from settings?

I have same webparts on different tenants with different colors/branding. Want to make my SPFx webpart more flexible and be able to change styles directly in webpart settings. In CEWP we could simply change .css file and this was Ok. What approach do You use now?.. Do You "recompile" webpart every time, or use external css files?

As I understand I can put my styles in external css file, and import it. Something like this:

enter image description here

But in this case I have external dependencies, as I understand it is not recommended SPFx should have all inside it, so maybe webpart settings is a good place..

update: Not sure if best way, but added "Custom CSS" webpart string property, and in constructor something like this:

  constructor(props: IMyWebpartProps) {
    super(props);

    if(props.customCss && (props.customCss).trim()!= '') {
      console.log('Load custom Css..');
      SPComponentLoader.loadCss((props.customCss).trim());

    } else {

      console.log(`Load out-of-box css..`);
      require('./styles.css');
    }
  }

This works for simple webparts. For something with carousels/sliders there could be problems and there works only "import" (instead of require). Not sure how to do dynamic styles import..

1 Answer 1

1

Referencing external dependencies isn't really a bad thing, the bad thing is when you want to bundle these dependencies in your bundle itself. Waldek Mastykarz has a post about this, bottom line is to keep the external dependencies external and not to bundle them in your project. Here's a link to Waldek's post: https://blog.mastykarz.nl/bundling-external-frameworks-sharepoint-framework-client-side-web-parts-bad-idea/

1
  • Thank You for response Mohamed! For me it is more about "portability".. Want to deploy same webpart, and quickly change colors (without webpart rebuild. For example orange icon for one client, blue for different). That's why was looking at webpart settings..
    – Gennady G
    Commented May 29, 2020 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.