forked from kitt-digital/vite-plugin-twig-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (60 loc) · 1.9 KB
/
index.js
File metadata and controls
68 lines (60 loc) · 1.9 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
// file system
const { readFileSync } = require('fs');
const { extname } = require('path');
// render functions
const { retrieveOptions, configureTwig, renderTemplate } = require('./tasks');
let viteLoaderConfigured = false;
/**
* @param {import('.').Options} options
* @returns {import('vite').Plugin}
*/
module.exports = (options) => {
const {
index = null,
filters = {},
functions = {},
globals = {},
settings = {}
} = options || retrieveOptions();
configureTwig({ filters, functions });
return {
name: 'vite-plugin-twig-loader',
transformIndexHtml: {
enforce: 'pre',
async transform(html) {
return index
? await renderTemplate(index, { ...globals }, settings)
: html;
}
},
async load(path) {
if (extname(path) !== '.twig') return;
const twig = await renderTemplate(path, { ...globals }, settings);
const input = readFileSync(path, 'utf8');
console.log('configured vite from twig loader');
let configurationCode = '';
if(!viteLoaderConfigured) {
configurationCode = `
console.log('configuring vite');
${Object.entries(filters || {}).map(([name, filter]) => `Twig.extendFilter('${name}', ${filter.toString()});`).join('\n')}
`;
viteLoaderConfigured = true;
}
return `
import Twig from 'twig';
${configurationCode}
export const path = ${JSON.stringify(path)};
export const ctx = ${JSON.stringify(input)};
export const globals = ${JSON.stringify({ ...globals })};
export const settings = ${JSON.stringify(settings)};
export const render = (data) => Twig.twig({data: ctx}).render(data);
export default ${JSON.stringify(twig)};
`;
},
handleHotUpdate({ file, server }) {
if (extname(file) === '.twig') {
server.ws.send({ type: 'full-reload' })
}
}
};
};