当您使用 Gatsby 时,您可以使用加载器,在这种情况下,您可以获得变量名 "less-vars-loader!antd/lib/style/themes/default.less"
这对于没有变量的简单的 less 工作表可以很好地工作,但是这对于 Antd 来说效果不佳,因为它们设置了一个变量@primary-color: @blue-6;
。
import React from "react"
import { Button } from 'antd';
import styled, { ThemeProvider } from "styled-components"
import Layout from "../components/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>
);
正如所Promise的,我正在添加我的示例 webpack 加载器来解析 antd 变量。它确实解析了大约 600 个变量,但它仍然以"JavaScript evaluation error: 'ReferenceError: colorPalette is not defined'"
. 这对于不需要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 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] of Object.entries( root.variables() ) ){
ret[name.replace( varRgx, "" )] = variable.value.eval( evalEnv ).toCSS();
}
return ret;
};
return `module.exports = ${JSON.stringify( await resolveVariables() )};`;
};
这可以用 调用import DefaultTheme from "./LESSLoader!antd/lib/style/themes/default.less"
。