umi3+React:使用less变量自定义颜色主题(less-vars-to-js)

第一种方法,不使用插件,直接直接theme配置,然后即可直接在less文件中使用在此定义 的变量。
https://v3.umijs.org/zh-CN/config#theme

export default {
  theme: {
    '@primary-color': '#1DA57A',
  },
};

第二种使用less-vars-to-js,将less文件转化为js对象

src\assets\css\index.less

@theme-color: '#888';

src\theme\variables.ts

import lessToJs from 'less-vars-to-js';
import path from 'path';
import fs from 'fs';

const themeVariables = lessToJs(
  fs.readFileSync(path.join(__dirname, '../assets/css/index.less'), 'utf8'),
);

console.log('themeVariables',themeVariables);

export default themeVariables;

umi3+React:使用less变量自定义颜色主题(less-vars-to-js)_第1张图片
.umirc.ts

import { defineConfig } from 'umi';
import theme  from './src/theme/variables';

export default defineConfig({
  nodeModulesTransform: {
    type: 'none',
  },
  fastRefresh: {},
  title: 'umi3+React-自学项目',
  metas: [
    {
      name: 'description',
      content: 'jishuuuu。',
    }, {
      name: 'keywords',
      content: 'umi, umijs',
    },
    {
      name: 'roots',
      content: 'umi, umijs',
    }
  ],
  // ssr:{}
  theme: theme,
});

应用

src\pages\NoteBook\index.tsx

import './index.less';

export default function NoteBook() {

    const goPage = (url) => {
        const element = document.createElement('a');
        element.href = url
        element.target = '_blank'
        element.click()
  
    }
    return (
        <>
            hello
            <button onClick={() => {
                goPage('//baidu.com')
            }}>点击跳转</button>
            <br />
            <div className="box-note-book">
                helllo
            </div>
        </>
    )
}

src\pages\NoteBook\index.less

.box-note-book {
  height: 200px;
  width: 300px;
  background-color: @theme-color;
}

你可能感兴趣的:(Umi框架,React全家桶系列,javascript,react.js,less,Umi3.js)