1- import { resolve } from 'path' ;
1+ import { dirname , resolve } from 'path' ;
2+ import { fileURLToPath } from 'url' ;
23import { defineConfig } from 'vite' ;
34import { viteStaticCopy } from 'vite-plugin-static-copy' ;
45
5- const viteGoogleAppsScript = ( ) => ( {
6- name : 'vite-appscript-exports' ,
7- generateBundle ( outputOptions , bundle ) {
8- Object . values ( bundle ) . forEach ( ( bundleChunk ) => {
9- const isJavaScriptFile = bundleChunk . fileName . endsWith ( '.js' ) ;
10- const isValidChunk = bundleChunk . type === 'chunk' && bundleChunk . code ;
11- const hasExports = bundleChunk . exports ?. length > 0 ;
12- if ( isJavaScriptFile && isValidChunk && hasExports ) {
13- const { name : libraryNamespace } = outputOptions ;
14- const globalFunctions = bundleChunk . exports . map (
15- ( fnName ) => `const ${ fnName } = (...args) => ${ libraryNamespace } .${ fnName } (...args);`
16- ) ;
17- bundleChunk . code = [ bundleChunk . code , ...globalFunctions ] . join ( '\n' ) ;
18- }
19- } ) ;
6+ const __filename = fileURLToPath ( import . meta. url ) ;
7+ const __dirname = dirname ( __filename ) ;
8+
9+ /**
10+ * Author: Amit Agarwal (amit@labnol.org)
11+ * Description: This is a custom Vite plugin to expose the functions from the bundled IIFE module
12+ * to the global scope. This is necessary for Google Apps Script to call
13+ * functions like onOpen(e) or other custom functions directly.
14+ * @returns {import('vite').Plugin }
15+ */
16+ const viteExposeGasFunctions = ( ) => ( {
17+ name : 'vite-expose-gas-functions' ,
18+ generateBundle ( options , bundle ) {
19+ const entryChunk = Object . values ( bundle ) . find ( ( chunk ) => chunk . type === 'chunk' && chunk . isEntry ) ;
20+ if ( entryChunk ) {
21+ const exposureCode = entryChunk . exports
22+ . map ( ( fnName ) => `function ${ fnName } () { return ${ options . name } .${ fnName } .apply(this, arguments); }` )
23+ . join ( '\n' ) ;
24+ entryChunk . code += `\n\n${ exposureCode } ` ;
25+ }
2026 } ,
2127} ) ;
2228
@@ -32,19 +38,18 @@ const targets = [
3238] ;
3339
3440export default defineConfig ( ( { mode } ) => ( {
35- plugins : [ viteGoogleAppsScript ( ) , viteStaticCopy ( { targets } ) ] ,
41+ plugins : [ viteExposeGasFunctions ( ) , viteStaticCopy ( { targets } ) ] ,
3642 build : {
37- target : " es2020" ,
43+ target : ' es2020' ,
3844 minify : mode !== 'development' ,
39- outDir : resolve ( process . cwd ( ) , 'dist' ) ,
45+ outDir : resolve ( __dirname , 'dist' ) ,
4046 lib : {
41- entry : resolve ( process . cwd ( ) , 'src/index.js' ) ,
47+ entry : resolve ( __dirname , 'src/index.js' ) ,
4248 name : 'app' ,
4349 formats : [ 'iife' ] ,
4450 } ,
4551 rollupOptions : {
4652 output : {
47- extend : false ,
4853 entryFileNames : 'code.js' ,
4954 } ,
5055 } ,
0 commit comments