Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -16,14 +16,45 @@ module.exports = function (source) {
compiler: Joi.func(),
parser: Joi.func(),
globals: Joi.array().single(),
locals: Joi.object()
locals: [Joi.object(), Joi.func()]
})

// validate options
const validated = Joi.validate(_opts, schema)
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)

Expand Down