-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.ts
62 lines (52 loc) · 1.83 KB
/
index.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
57
58
59
60
61
62
import {Plugin, ResolvedConfig} from "vite";
import ejs from "ejs";
// ShortHand for EjsOptions or Undefined
type EjsRenderOptions = ejs.Options & { async?: false };
type EjsRenderOptionsFn = (config: ResolvedConfig) => EjsRenderOptions;
type ViteEjsPluginDataType = Record<string, any> | ((config: ResolvedConfig) => Record<string, any>);
type ViteEjsPluginOptions = { ejs?: EjsRenderOptions | EjsRenderOptionsFn };
/**
* Vite Ejs Plugin Function
* See https://github.com/trapcodeio/vite-plugin-ejs for more information
* @example
* export default defineConfig({
* plugins: [
* vue(),
* ViteEjsPlugin({foo: 'bar'})
* ],
* });
*/
function ViteEjsPlugin(data: ViteEjsPluginDataType = {}, options?: ViteEjsPluginOptions): Plugin {
let config: ResolvedConfig;
return {
name: "vite-plugin-ejs",
// Get Resolved config
configResolved(resolvedConfig) {
config = resolvedConfig;
},
transformIndexHtml: {
order: "pre",
handler(html) {
if (typeof data === "function") data = data(config);
let ejsOptions = options && options.ejs ? options.ejs : {};
if (typeof ejsOptions === "function") ejsOptions = ejsOptions(config);
html = ejs.render(
html,
{
NODE_ENV: config.mode,
isDev: config.mode === "development",
...data
},
{
// setting views enables includes support
views: [config.root],
...ejsOptions,
async: false // Force sync
}
);
return html;
}
}
};
}
export {ViteEjsPlugin, ejs}