Bundle many LESS files into a single LESS file

988 Views Asked by At

I'm making a library containing some generic UI components, some kind of Bootstrap. Suppose I have the following LESS files structure:

button.less
checkbox.less
index.less
variables.less

Each component style file has @import "variables.less";. Index file imports all components files. Now I would like to distribute library.less and variables.less files into a package.

How do I bundle the index file? I used to concatenate all the files and remove repeated @import "variables"; line using regexps, maybe there is a Less API for doing this.

1

There are 1 best solutions below

1
Zohaib Ijaz On

You can use less-bundle https://www.npmjs.com/package/less-bundle

// variables.less
@red: #ff0000;
@grey: #cccccc;

// button.less
@import 'variables.less';
.btn-danger {
     background: @color;
}

// checkbox.less
@import 'variables.less';
input[type='checkbox'] {
   background: @grey;
}

// index.less
@import 'button.less';
@import 'checkbox.less';

Here is main code to do that.

// bundler.js
const path = require('path')
const bundle = require('less-bundle');
const srcFile = path.join(__dirname, './index.less');

bundle({
  src: srcFile,
  dest: path.join(__dirname, './bundle.less')
}, function (err, data) {
  console.log('Error Bundle', err, data);
});

Run bundler.js using command node bundler.js and it will create a bundle.less file containing all styles.

// bundle.less
@red: #ff0000;
@grey: #cccccc;

.btn-danger {
     background: @color;
}

input[type='checkbox'] {
   background: @grey;
}