Umi: how to define global less variable ?

Created on 16 Nov 2018  ·  5Comments  ·  Source: umijs/umi

I've try this :

// config.js
theme: {
  a: '100px'
}

// index.less
width: @a;

It's not work. which @a is undefined.

I also try this:

// config.js
lessLoaderOptions: {
    globalVars: {
      a: '300px',
    },
}

// index.less
width: @a;

It's still not work.

Please tell me how to define a global less variable so I can use it in many different .less file ?

thx!

Most helpful comment

All 5 comments

创建一个 _var.less 文件,里面去定义变量,然后其他 less @import 进来即可

是的

umi config 文件里面有 相关 样式loader 可以写参数
比如我sass-loader

  sass: {
      data: '@import "_base";\n', // 变量写这里
      sourceMap: true,
      includePaths: [path.resolve(__dirname, "./src/styles")]
  },
  1. 在src目录下创建一个variable.less
  2. 配置.umirc.ts
import { IConfig } from 'umi-types';
import path from 'path';
import fs from 'fs';

const config: IConfig =  {
  ...otherConfig,
  lessLoaderOptions: {
    globalVars: getLessVariables(path.resolve(__dirname, 'src/variable.less')),
  },
}


function getLessVariables(filepath: string) {
  const varsContent: string = fs.readFileSync(filepath).toString('utf-8');
  const vars: {[name: string]: string} = {};
  if (varsContent) {
    const list = varsContent.match(/@\S*\s?:\s?\S*;/g);
    if (list) {
      list.forEach((variable) => {
        const m: string[] | null = variable.match(/@(\S*)\s?:\s?(\S*);/);
        m && (vars[m[1]] = m[2]);
      })
    }
  }
  return vars;
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ddzy picture ddzy  ·  3Comments

nguyenhuutinh picture nguyenhuutinh  ·  3Comments

stoneWeb picture stoneWeb  ·  3Comments

haiing picture haiing  ·  3Comments

ironyfive picture ironyfive  ·  3Comments