将多个LESS文件捆绑成一个单独的LESS文件

4

我正在制作一个包含一些通用UI组件的库,类似于Bootstrap。假设我有以下LESS文件结构:

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

每个组件样式文件都有@import "variables.less";。Index文件导入所有组件文件。现在我想将library.less和variables.less文件分发到一个包中。
如何捆绑索引文件?我曾经使用正则表达式连接所有文件并删除重复的@import "variables";行,也许有一个Less API可以做到这一点。

不,Less没有生成less文件的功能。所以对于这种东西,你只能自己动手了。顺便说一句,除了使“包”更易读之外,没有理由删除冗余导入,因为任何后续对同一文件的导入都没有任何影响(请参见文档)。 - seven-phases-max
1个回答

4
您可以使用less-bundlehttps://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';

以下是主要代码。

// 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);
});

使用命令node bundler.js运行bundler.js,它将创建一个名为bundle.less的文件,其中包含所有样式。

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

.btn-danger {
     background: @color;
}

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

1
这应该被接受的答案,解决了我的确切使用情况。 - Ryan Killeen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接