Jimmy
Jimmy

Reputation: 3860

How to use Less variables without importing stylesheet

I have a react application with a similar structure to the below:

- src/
  - index.tsx
  - index.less
  - app/
    - app.tsx
    - app.less
  - styles/
    - _colors.less

I want to use my application so that I don't have to import every stylesheet. What I would like is the following:

-- index.less --

@import "~styles/_colors";

-- _colors.less --

@blue: #14A8F3;

-- app.less --

.sampleApp {
  background: @blue;
}

How can I use my less variables in files such as app.less without importing the necessary stylesheets, given that I am importing the stylesheet (in this case, _colors.less) in the root of the application?

Is there something I need to do in webpack? Here is what my current webpack looks like. Thanks!

webpack.common.js:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const SRC_DIR = path.resolve(__dirname, 'src');

const entry = [
  'babel-polyfill',
  `${SRC_DIR}/index.tsx`,
  `${SRC_DIR}/index.less`,
];

const rules = [
  {
    test: /\.tsx?$/,
    use: 'ts-loader',
    exclude: /node_modules/,
  },
  {
    test: /\.css$/,
    use: [
      MiniCssExtractPlugin.loader,
      'css-loader',
    ],
  },
  {
    test: /\.less$/,
    use: [
      MiniCssExtractPlugin.loader,
      'css-loader',
      'postcss-loader',
      {
        loader: 'less-loader',
        options: { javascriptEnabled: true },
      },
    ],
  },
];

const plugins = [
  new MiniCssExtractPlugin({
    filename: 'application.css',
  }),
];

const config = {
  entry,
  output,
  module: { rules },
  plugins,
  resolve,
};

module.exports = config;

Upvotes: 0

Views: 918

Answers (1)

felixmosh
felixmosh

Reputation: 35503

You can use the additionaldata option of less-loader in order to prepend your variables file.

The idea is to read the file, and return it's content.

// webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "less-loader",
            options: {
              additionalData: (content, loaderContext) => {
                const variables = fs.readFileSync('path-to-your/_varaibles.less');

                return variables + content;
              },
            },
          },
        ],
      },
    ],
  },
};

Upvotes: 2

Related Questions