Skip to content

Commit bc6c773

Browse files
akxbebraw
authored andcommitted
Add support for async templates (#21)
1 parent f16bf21 commit bc6c773

File tree

4 files changed

+24
-6
lines changed

4 files changed

+24
-6
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ const config = {
9393
9494
Use [@vxna/mini-html-webpack-template](https://www.npmjs.com/package/@vxna/mini-html-webpack-template) to add an app container div, a favicon, meta tags, inline JavaScript or CSS.
9595
96-
Or define a template function to generate your own code:
96+
Or define a template function to generate your own code.
97+
98+
The template function may return a string or a Promise resolving to a string.
9799
98100
```js
99101
const MiniHtmlWebpackPlugin = require('mini-html-webpack-plugin');

__snapshots__/test.js.snap

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ exports[`additional head 1`] = `
2828
</html>"
2929
`;
3030
31+
exports[`custom async template 1`] = `"<div>Pizza</div>"`;
32+
3133
exports[`custom chunks 1`] = `
3234
"<!DOCTYPE html>
3335
<html lang=\\"en\\">

index.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,10 @@ class MiniHtmlWebpackPlugin {
2323

2424
const options = Object.assign({}, { publicPath }, context, files);
2525

26-
compilation.assets[filename] = new RawSource(
27-
(template || defaultTemplate)(options)
28-
);
29-
30-
callback();
26+
Promise.resolve((template || defaultTemplate)(options)).then(source => {
27+
compilation.assets[filename] = new RawSource(source);
28+
callback();
29+
});
3130
}
3231

3332
apply(compiler) {

test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,21 @@ test('custom template', () => {
106106
});
107107
});
108108

109+
test('custom async template', () => {
110+
return compiler(
111+
{},
112+
getConfig({
113+
context: { title: 'Pizza' },
114+
template: ({ title }) => {
115+
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
116+
return delay(50).then(() => `<div>${title}</div>`);
117+
},
118+
})
119+
).then(result => {
120+
expect(result.compilation.assets['index.html']._value).toMatchSnapshot();
121+
});
122+
});
123+
109124
test('custom filename', () => {
110125
const filename = 'pizza.html';
111126
return compiler({}, getConfig({ filename })).then(result => {

0 commit comments

Comments
 (0)