Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read Less variables in Javascript?

How can I read less variables in javascript like less-vars-to-js?

I'm working on a React project(webpack2、less etc), but not SSR(node environment),so I can't use fs or node-glob module.

Some people suggest me writting a webpack loader myself :( i'm not really familiar with that... And I already used less-loader...

javascript

import lessToJs from 'less-vars-to-js';
import styles from './style.less';

const jsStyle = lessToJs(styles); => Uncaught TypeError: sheet.match is not a function

const mycomponent = (
  <MyComponent
    className={styles.nav}
    tintColor={jsStyle['@tint-color']}
  />
);

less

@import "../../../themes/theme.web.less";

@tint-color: grey;

.nav {
  background-color: @tint-color;
}

webpack

config.module.rules.push({
  test: /\.less$/,
  exclude: /node_modules/,
  use: [
    { loader: 'style-loader' },
    {
      loader: 'css-loader',
      options: {
        modules: true,
        importLoaders: 1,
      },
    },
    { loader: 'postcss-loader' },
    { loader: 'less-loader' },
  ],
});
like image 697
Kim Avatar asked May 19 '17 07:05

Kim


1 Answers

As I mentioned in my comment you could implement custom loader. Something like this (haven't tested)

//utils/less-var-loader.js
const lessToJs = require('less-vars-to-js')

module.exports = function(content) {
  return `module.exports = ${JSON.stringify(lessToJs(content))}`
}

and then

import * as styles from '!!./utils/less-var-loader!./style.less'

Double bang !! to ignore preconfigured loaders.

like image 170
Yury Tarabanko Avatar answered Oct 16 '22 06:10

Yury Tarabanko