Skip to content

Commit

Permalink
feat: load a JS config file (#18)
Browse files Browse the repository at this point in the history
* Load a custom config: pug.config.js

* Create a config section in the README

* Do lint

* Don't swallow required module errors

* Check that used root level keys are valid

* Add comment explaining validation
  • Loading branch information
xbc5 committed Feb 4, 2022
1 parent 528be32 commit 0a2f653
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,19 @@ Add support for [Pug].
$ npm install hexo-renderer-pug --save
```

## Config
PugJS [options](https://pugjs.org/api/reference.html#options) are supported. These are the options passed into [compile()](https://pugjs.org/api/reference.html#pugcompilesource-options).

Create a `pug.config.js` in your project root:

```js
module.exports = {
compile: { // Passed to compile().
basedir: process.cwd(),
// ...Other options.
}
// No other methods are supported for now.
}
```

[Pug]: http://pugjs.org/
28 changes: 25 additions & 3 deletions lib/pug.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
'use strict';

const path = require('path');
const pug = require('pug');

const configPath = path.join(process.cwd(), 'pug.config');
const defaultConfig = { compile: {} }; // avoids key errors

let hasConfig = true;
try {
require.resolve(configPath);
} catch {
hasConfig = false;
}

const config = hasConfig ? require(configPath) : defaultConfig;

// Validate non-standard keys -- e.g. 'compile'.
const hasProp = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
const invalidKeys = Object.keys(config).filter(k => !hasProp(defaultConfig, k));
if (invalidKeys.length > 0) {
throw Error(`Unsupported PUG config keys: ${invalidKeys.join(', ')}`);
}

function pugCompile(data) {
return pug.compile(data.text, {
filename: data.path
});
const opts = {
...config.compile,
filename: data.path // always used
};
return pug.compile(data.text, opts);
}

function pugRenderer(data, locals) {
Expand Down

0 comments on commit 0a2f653

Please sign in to comment.