我需要在.js和.less文件之间共享一个常量。我对此的解决方案包括两个步骤:
但是我找不到根据所需模块从一个源文件创建两个模块的方法。
我的条件加载程序源代码可以完成以下任务:
module.exports = function(content, sourceMap) {
var _ = require('lodash');
var loaderUtils = require('loader-utils');
var reasonResource = this._module.reasons[0].module.resource;
var reasonResourceExtension = _.last(reasonResource.split('.'));
switch (reasonResourceExtension)
{
case 'js':
case 'const':
var query = loaderUtils.parseQuery(this.query);
if(query.cacheable && this.cacheable)
this.cacheable();
return content;
break;
case 'less':
var consts = this.exec(content, this.resource);
return JSON.stringify(consts);
break;
default:
throw new Error('Not supported import .const modules from ' + reasonResourceExtension.green);
}
};
问题出在less-loader
。它未应用在中配置的装载程序webpack.config.js
。因此解决方案是增加对less-loader
加载程序列表进行参数设置的功能
然后就可以开始写Constants.const
内容了
export.modules = { debug: true }
然后要求 Utilities.less
@import (reference) 'Const.const';
应用此装载机
module.exports = function(content, sourceMap) {
var _ = require('lodash');
var loaderUtils = require('loader-utils');
var reasonResource = this._module.reasons[0].module.resource;
var reasonResourceExtension = _.last(reasonResource.split('.'));
var query = loaderUtils.parseQuery(this.query);
switch (reasonResourceExtension)
{
case 'js':
case 'const':
if(query.cacheable && this.cacheable)
this.cacheable();
return content;
break;
case 'less':
if(query.cacheable && this.cacheable)
this.cacheable();
var consts = this.exec(content, this.resource);
var str = '';
(function append(consts, prefix = '')
{
for (var key in consts)
{
let value = consts[key];
if (value.constructor != Object) {
str += '@' + prefix + key + ': ' + toLessCssValue(consts[key]) + ';';
} else {
throw new Error('Nested objects not supported in .const files');
}
}
}(consts));
return str;
break;
default:
throw new Error('Not supported import .const modules from ' + reasonResourceExtension.green);
}
function toLessCssValue(value) {
if (isNaN(value)) {
return value;
} else {
return 'unit(' + value + ', px)';
}
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句