最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using Ant Design Variables in Styled Components - Stack Overflow

programmeradmin3浏览0评论

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) within a styled ponent. Something like this:

const StyledButton = styled(Button)`
  background-color: @primary-color
`

I did a little research and found two libraries that may be able to help, but I couldn't figure out how to get them to work (at least not in a Gatsby setting). These are the libraries:

The Styless package has an example of how to get Less variables to work in Styled Compoments: .js.

However, I have not been able to get that example to work on my Gatsby site -- whether I try implementing it on my base layout ponent, in gatsby-ssr.jsor gatsby-browser.js.

So, I am wondering -- is there a way to be able to access Less variables inside of a Styled Component in a GatsbyJS site (either with these libraries or without)? If so, how?

Thanks.

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) within a styled ponent. Something like this:

const StyledButton = styled(Button)`
  background-color: @primary-color
`

I did a little research and found two libraries that may be able to help, but I couldn't figure out how to get them to work (at least not in a Gatsby setting). These are the libraries:

  • https://github./michaeltaranto/less-vars-to-js
  • https://github./jean343/styless

The Styless package has an example of how to get Less variables to work in Styled Compoments: https://github./jean343/styless/blob/master/examples/Theme.js.

However, I have not been able to get that example to work on my Gatsby site -- whether I try implementing it on my base layout ponent, in gatsby-ssr.jsor gatsby-browser.js.

So, I am wondering -- is there a way to be able to access Less variables inside of a Styled Component in a GatsbyJS site (either with these libraries or without)? If so, how?

Thanks.

Share Improve this question edited Dec 24, 2019 at 17:26 Moshe asked Dec 24, 2019 at 14:09 MosheMoshe 7,04121 gold badges77 silver badges137 bronze badges 1
  • You could also simply do: import 'antd/dist/antd.variable.min.css'; and then use var(). – aderchox Commented Jun 8, 2022 at 21:05
Add a ment  | 

2 Answers 2

Reset to default 5

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:

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

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

export default () => {
    return <StyledButton>button</StyledButton>
}

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

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

import React from "react"
import { Button } from 'antd';
import styled, { ThemeProvider } from "styled-ponents"
import Layout from "../ponents/layout"
import DefaultTheme from "less-vars-loader!antd/lib/style/themes/default.less"
import "antd/dist/antd.css";

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

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

export default () => (
    <ThemeProvider theme={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 = await new Promise( 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 piling`, e );
                }
                resolve( root );
            } );
        } );
        if( !root ) return;

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

        const ret = {};
        for( let [name, variable] of Object.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".

发布评论

评论列表(0)

  1. 暂无评论