Skip to content Skip to sidebar Skip to footer

Using Ant Design Variables In Styled Components

I am using Ant Design in conjunction with Styled Components inside of a GatsbyJS site. I would like to be able to access the Ant Design variables (which are written in Less) withi

Solution 1:

If you are only looking at getting the Antd variable names in Styled Components, you could instead use the import option of styless. This is much simpler and there is no need to parse any variables.

In your .babelrc, use this code for importing styless.

{"plugins":[["styless",{"import":"~antd/lib/style/themes/default.less","lessOptions":{"javascriptEnabled":true}}]]}

Then, all of the client code can be simplified to:

importReactfrom"react"import { Button } from'antd';
import styled from"styled-components"import"antd/dist/antd.css";

constStyledButton = styled( Button )`
  background-color: @primary-color;
`;

exportdefault () => {
    return<StyledButton>button</StyledButton>
}

Do not forget to delete the .cache folder for the effects to take place.

Solution 2:

As you are using Gatsby, you can use loaders, in this case you could get the variable names with "less-vars-loader!antd/lib/style/themes/default.less"

This would work fine with simple less sheets without variables, but this does not work quite well for Antd as they set a variable @primary-color: @blue-6;.

importReactfrom"react"import { Button } from'antd';
import styled, { ThemeProvider } from"styled-components"importLayoutfrom"../components/layout"importDefaultThemefrom"less-vars-loader!antd/lib/style/themes/default.less"import"antd/dist/antd.css";

constStyledButton = styled( Button )`
  background-color: @primary-color;
`;

constApp = () => (
    <Layout><StyledButton>Hi people</StyledButton></Layout>
);
console.log( "DefaultTheme", DefaultTheme["primary-color"] ); // Here, this shows @blue-6DefaultTheme["primary-color"] = "blue"; // For demo purpose, setting the value here.exportdefault () => (
    <ThemeProvidertheme={DefaultTheme}><App/></ThemeProvider>
);

As promised, I am adding my sample webpack loader to resolve the antd variables. It does resolve about 600 variables, but it still fails with "JavaScript evaluation error: 'ReferenceError: colorPalette is not defined'". This can be useful for projects which do not require javascriptEnabled.

const less = require( "less" );
const varRgx = /^[@$]/;

module.exports = async source => {
    const resolveVariables = async () => {
        const root = awaitnewPromise( resolve => {
            const parseOpts = {
                javascriptEnabled: true,
                paths: ["node_modules/antd/lib/style/themes/"],
            };
            less.parse( source, parseOpts, ( e, root, imports, options ) => {
                if( e ){
                    console.error( `LESSLoader - Error compiling`, e );
                }
                resolve( root );
            } );
        } );
        if( !root ) return;

        const evalEnv = new less.contexts.Eval();
        evalEnv.frames = [root];
        evalEnv.javascriptEnabled = true;

        const ret = {};
        for( let [name, variable] ofObject.entries( root.variables() ) ){
            ret[name.replace( varRgx, "" )] = variable.value.eval( evalEnv ).toCSS();
        }
        return ret;
    };

    return`module.exports = ${JSON.stringify( await resolveVariables() )};`;
};

This can be called with import DefaultTheme from "./LESSLoader!antd/lib/style/themes/default.less".

Post a Comment for "Using Ant Design Variables In Styled Components"