-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvite-nunjucks.plugin.ts
56 lines (52 loc) · 1.91 KB
/
vite-nunjucks.plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { readFile } from 'node:fs/promises';
import { basename, dirname, resolve as resolvePath } from 'node:path';
import { ConfigureOptions, Environment } from 'nunjucks';
import { HmrContext, IndexHtmlTransformContext, IndexHtmlTransformResult, Plugin } from 'vite';
export interface NunjucksPluginOptions {
options: Partial<ConfigureOptions>;
locals: object; // nunjucks template variables
}
const nunjucksOptions: ConfigureOptions = {
autoescape: true,
lstripBlocks: true,
noCache: true,
throwOnUndefined: true,
trimBlocks: true
};
export default (options: Partial<NunjucksPluginOptions> = {}): Plugin => {
const locals: object = options.locals ?? {};
const sourcePaths: string[] = [];
return {
name: 'nunjucks',
enforce: 'pre',
handleHotUpdate: (context: HmrContext): void | [] => {
if (!sourcePaths.includes(context.file)) return;
context.server.ws.send({ type: 'full-reload' });
return [];
},
transformIndexHtml: {
order: 'pre',
handler: async (html: string, context: IndexHtmlTransformContext): Promise<IndexHtmlTransformResult | void> =>
new Promise((resolve, reject) => {
new Environment(
{
async: true,
getSource: (name, callback) => {
const path = resolvePath(dirname(context.filename), name);
sourcePaths.push(path);
readFile(path)
.then(src => {
callback(undefined, { src: src.toString(), path, noCache: !!nunjucksOptions.noCache });
})
.catch(error => (callback as (error: Error) => void)(error));
}
},
nunjucksOptions
).renderString(html, { ...locals, ...locals[basename(context.path)] }, (error, rendered) => {
if (error) reject(error);
else resolve(rendered as string);
});
})
}
};
};