Re-use CSS in LWC using CSS Module

cssLibrary.css:

h1 {
    text-align: center;
    font-weight: bold;
    font-size: large;
    color: black;
}

.bgCSS {
    background: black;
    color: white;
    font-weight: bold;
}

cssLibrary.js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

sample.html:

<template>
    <div class="slds-box slds-theme--default">
        <h1>
            Testing in Sample
        </h1>
        <div class="bgCSS">
            Testing Sample
        </div>
    </div>
</template>

sample.js:

import { LightningElement } from 'lwc';

export default class Sample extends LightningElement {}

sample.css:

@import 'c/cssLibrary';

sample.js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply