From 8af182adee90e23194904807779c2a8cd12b39a5 Mon Sep 17 00:00:00 2001 From: Nick Doering Date: Thu, 27 Jul 2017 13:42:32 -0700 Subject: [PATCH] Added parseOptions from reshape-loader --- lib/index.js | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index cafebeb..4df283d 100644 --- a/lib/index.js +++ b/lib/index.js @@ -4,7 +4,7 @@ const Joi = require('joi') module.exports = function (source) { this.cacheable && this.cacheable(true) - const _opts = this.query || {} + const _opts = parseOptions.call(this, this.query) || {} const schema = Joi.object().keys({ filename: Joi.string().default(this.resourcePath), pretty: Joi.boolean().default(true), @@ -16,7 +16,7 @@ module.exports = function (source) { compiler: Joi.func(), parser: Joi.func(), globals: Joi.array().single(), - locals: Joi.object() + locals: [Joi.object(), Joi.func()] }) // validate options @@ -24,6 +24,37 @@ module.exports = function (source) { if (validated.error) { throw validated.error } const opts = validated.value + // Allows any option to be passed as a function which gets webpack's context + // as its first argument, in case some info from the loader context is necessary. Courtesy of Reshape-Loader. + function parseOptions (opts) { + return removeEmpty({ + plugins: convertFn.call(this, opts.plugins), + locals: convertFn.call(this, opts.locals), + filename: convertFn.call(this, opts.filename), + parserOptions: convertFn.call(this, opts.parserOptions), + generatorOptions: convertFn.call(this, opts.generatorOptions), + runtime: convertFn.call(this, opts.runtime), + parser: convertFnSpecial.call(this, opts.parser), + multi: convertFn.call(this, opts.multi) + }) + } + + //Passes context to functions + function convertFn (opt) { + return typeof opt === 'function' ? opt(this) : opt + } + + //Pass context to function if convert is true. + function convertFnSpecial (opt) { + return typeof opt === 'function' && opt.convert ? opt(this) : opt + } + + //Remove empty elements from objects + function removeEmpty (obj) { + Object.keys(obj).forEach((key) => (obj[key] == null) && delete obj[key]) + return obj + } + // compile the template to a function const tpl = pug.compile(source, opts)