1- import { Plugin , ResolvedConfig } from "vite" ;
1+ import { Plugin , ResolvedConfig , UserConfig } from "vite" ;
22import ejs from "ejs" ;
33
44// ShortHand for EjsOptions or Undefined
5- type EjsRenderOptions = ( ejs . Options & { async : false } ) | undefined ;
5+ type EjsRenderOptions = ejs . Options & { async ?: false } ;
6+ type EjsRenderOptionsFn = ( config : ResolvedConfig ) => EjsRenderOptions ;
67type ViteEjsPluginDataType = Record < string , any > | ( ( config : ResolvedConfig ) => Record < string , any > ) ;
7- type ViteEjsPluginOptions = { ejs : EjsRenderOptions } ;
8+ type ViteEjsPluginOptions = { watchEjsFiles ?: boolean , ejs ? : EjsRenderOptions | EjsRenderOptionsFn } ;
89
910/**
1011 * Vite Ejs Plugin Function
11- *
12+ * See https://github.com/trapcodeio/vite-plugin-ejs for more information
1213 * @example
1314 * export default defineConfig({
1415 * plugins: [
@@ -23,8 +24,13 @@ function ViteEjsPlugin(data: ViteEjsPluginDataType = {}, options?: ViteEjsPlugin
2324 return {
2425 name : "vite-plugin-ejs" ,
2526
27+ config ( config ) {
28+ // Add .ejs extension to watch files.
29+ if ( options && options . watchEjsFiles ) WatchEjsFiles ( config ) ;
30+ } ,
31+
2632 // Get Resolved config
27- configResolved ( resolvedConfig ) {
33+ configResolved ( resolvedConfig ) {
2834 config = resolvedConfig ;
2935 } ,
3036
@@ -34,6 +40,9 @@ function ViteEjsPlugin(data: ViteEjsPluginDataType = {}, options?: ViteEjsPlugin
3440 // config.isProduction
3541 try {
3642 if ( typeof data === "function" ) data = data ( config ) ;
43+ let ejsOptions = options && options . ejs ? options . ejs : { } ;
44+ if ( typeof ejsOptions === "function" ) ejsOptions = ejsOptions ( config ) ;
45+
3746
3847 html = ejs . render (
3948 html ,
@@ -42,7 +51,11 @@ function ViteEjsPlugin(data: ViteEjsPluginDataType = {}, options?: ViteEjsPlugin
4251 isDev : config . mode === "development" ,
4352 ...data
4453 } ,
45- options ?. ejs
54+ {
55+ views : [ config . root ] , // Set views directory that can be overwritten
56+ ...ejsOptions ,
57+ async : false // Force sync
58+ }
4659 ) ;
4760 } catch ( e : any ) {
4861 return e . message ;
@@ -54,4 +67,21 @@ function ViteEjsPlugin(data: ViteEjsPluginDataType = {}, options?: ViteEjsPlugin
5467 } ;
5568}
5669
70+
71+ function WatchEjsFiles ( config : UserConfig ) {
72+ // Add .ejs extension to watch files.
73+ // get watch config
74+ let watch = config . build ? config . build . watch : { } ;
75+
76+ // if none is defined, set to empty object
77+ if ( ! watch ) watch = { }
78+ // check if watch.include is defined and if not, set to empty array
79+ if ( ! watch . include ) watch . include = [ ] ;
80+ // if watch.include is not an array then convert to array
81+ if ( ! Array . isArray ( watch . include ) ) watch . include = [ watch . include ] ;
82+
83+ // Add ejs files to watch list
84+ watch . include . push ( "**/*.ejs" ) ;
85+ }
86+
5787export { ViteEjsPlugin , ejs }
0 commit comments