有没有办法多次要求一个文件作为不同的模块
我需要在我的.js和.less文件之间共享一个常量。 我的解决scheme包含两个步骤:
- 创build一个包含所有共享常量的.const扩展名的单独文件。 它有JavaScript模块的语法,将作为正常执行。
- 创build一个加载器,根据需要这个源文件的扩展名来改变源代码。 所以,如果要求.less文件,那么代码转换为较less的expression式
但我没有find从一个源文件创build两个模块的方式取决于需要的模块。
我的条件加载器的源代码,做的东西:
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); } };
您可以使用require loader语法在较less的文件中指定一个json-to-less加载器(不确定是否存在,但不应该很难写):
@import "!json-to-less-loader!constants.json";
然后,创build一个较less的文件( constants.less
),使这个导入和公开常量。 从那里,你可以正常导入constants.less
。
我能find一个相反的装载器( less-to-json-loader )。 所以你可以使用它并将你的常量存储在一个.less文件中,并创build一个constants.js
文件,用于导入并显示常量中的constants.less
。
constants.less
@test: 20rem; @test2: @test/2;
constants.js
module.exports = require("!less-to-json-loader!./constants.less");
问题在于less-loader
。 它不应用在webpack.config.js
configuration的webpack.config.js
。 所以解决scheme是添加能力,参数化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)'; } } };