Domanda

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..

È stato utile?

Soluzione

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/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top