How to use Aura Design Tokens in LWC

 Salesforce Spring 20 Release, you can style Lightning Web Components with Custom Aura Design Tokens.

aura-tokens-lwc

Aura Design Token Bundle:

A tokens bundle contains only one resource and a tokens collection definition. It contains markup for one or more tokens.

A tokens collection starts with the <aura:tokens> tag. It can only contain <aura:token> tags to define tokens. A token is a name-value pair, It only allows attributes for the <aura:token> tag are name and value.

Create an Aura Token Bundle:

To create lighting tokens, Setup --> Developer Console --> select File --> New --> Lightning Tokens.

Your first tokens bundle should be named defaultTokens. The tokens defined within defaultTokens are automatically accessible in your Lightning components. 

Syntax to add aura tokens in lwc

To use aura design tokens in your lwc component. 

background-color : var(--c-myBackgroundColor);

Here "var" is a CSS function used to access the token, "--c-" is a prefix you need to use and "myBackgroundColor" is the token name.

First create aura component for tokens

defaultTokens.tokens

<aura:tokens>
	<aura:token name="myTextFontFace" 
               value="'Salesforce Sans', Helvetica, Arial, sans-serif"/>
    <aura:token name="myTextFontWeight" value="Bold"/>
    <aura:token name="myBackgroundColor" value="#808080"/>
    <aura:token name="myTextColor" value="red"/>
    <aura:token name="myMarginForTable" value="5px"/>
</aura:tokens>

use aura tokens in lwc:

usingAuraDesignTokensInLWC.html

<template>
    <lightning-card title="Using Aura Token Bundle" icon-name="utility:custom_apps">
        <div class="slds-m-around_medium">
            <div>This is Sample Text, without any class</div>
            <div class="myTitleDiv">This is Sample Text, with custom CSS class with Aura design tokens</div>
        </div>
    </lightning-card>
</template>

usingAuraDesignTokensInLWC.js

import { LightningElement } from 'lwc';

export default class UsingAuraDesignTokensInLWC extends LightningElement {}

usingAuraDesignTokensInLWC.css

.myTitleDiv{
    color: var(--c-myTextColor); 
    background-color: var(--c-myBackgroundColor); 
}

usingAuraDesignTokensInLWC.js-meta.xml

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

Also found above code in Tech Shorts Git repo

Labels:
LWC
Join the conversation