[SalesForce] Is it possible to make one css or js in common to all the Lightning web components

Here is my situation, I have two (and soon more) LWC, inside each component, I have the classic : html, css, js and xml.

In my case, the first LWC is having many css properties in common with the other LWC : color of buttons, same font, etc.

I want to have a global CSS out and to that make all LWC share some common properties. How to do that ?

Same think for JS.

Additional information : I am using full-custom classes css (and my own js), I do not use any element from the lightning Library.

Best Answer

The easiest mechanism for sharing JS and CSS code between LWCs across a single project is essentially create an LWC for each (the JS and the CSS).

Each LWC contains just the code artifact for the JS or CSS code.

In other words, they're LWC's without HTML templates. The one will have your XML metadata descriptor and a JS module, the other will have the XML descriptor and the CSS file.

There are instructions for how to construct and consume these in the LWC documentation with an example each for CSS and for JS.

There is an example of this in the LWC Recipes sample app with the component importing JS from another module in the project.

Reading your comment above, I'd say that the best architecture for you is a larger scale library that encapsulates all your CSS assets (and the images that go with them) into a component that's consumed across your project. You might even want to look at packaging it as its own unmanaged package so you can simply install it using sfdx force:package:install. That way, the entire CSS library is its own project with its own development lifecycle.

Related Topic