11import { minifySync as swcMinify } from '@swc/core'
2+ import { rollup } from 'rollup'
23import fs from 'fs'
34import path from 'path'
45import { fileURLToPath } from 'url'
@@ -33,7 +34,7 @@ export async function compileAll(options = {}) {
3334 }
3435
3536 const variants = getVariantsToCompile ( options )
36- const baseCode = getCode ( )
37+ const bundledCode = await bundleCode ( )
3738
3839 const startTime = Date . now ( ) ;
3940 console . log ( `Starting compilation of ${ variants . length } variants...` )
@@ -44,7 +45,7 @@ export async function compileAll(options = {}) {
4445 const workerPool = Pool ( ( ) => spawn ( new Worker ( './worker-thread.js' ) ) )
4546 variants . forEach ( variant => {
4647 workerPool . queue ( async ( worker ) => {
47- await worker . compileFile ( variant , { ...options , baseCode } )
48+ await worker . compileFile ( variant , { ...options , bundledCode } )
4849 bar . increment ( )
4950 } )
5051 } )
@@ -56,11 +57,11 @@ export async function compileAll(options = {}) {
5657 console . log ( `Completed compilation of ${ variants . length } variants in ${ ( ( Date . now ( ) - startTime ) / 1000 ) . toFixed ( 2 ) } s` ) ;
5758}
5859
59- export function compileFile ( variant , options ) {
60- const baseCode = options . baseCode || getCode ( )
60+ export async function compileFile ( variant , options ) {
61+ const wrappedCode = wrapInstantlyEvaluatingFunction ( options . bundledCode || await bundleCode ( ) )
6162 const globals = { ...DEFAULT_GLOBALS , ...variant . globals }
6263
63- const code = minify ( baseCode , globals )
64+ const code = minify ( wrappedCode , globals )
6465
6566 if ( options . returnCode ) {
6667 return code
@@ -69,6 +70,10 @@ export function compileFile(variant, options) {
6970 }
7071}
7172
73+ function wrapInstantlyEvaluatingFunction ( baseCode ) {
74+ return `(function(){${ baseCode } })()`
75+ }
76+
7277export function compileWebSnippet ( ) {
7378 const code = fs . readFileSync ( relPath ( '../src/web-snippet.js' ) ) . toString ( )
7479 return `
@@ -95,9 +100,16 @@ function getVariantsToCompile(options) {
95100 return targetVariants
96101}
97102
98- function getCode ( ) {
99- // Wrap the code in an instantly evaluating function
100- return `(function(){${ fs . readFileSync ( relPath ( '../src/plausible.js' ) ) . toString ( ) } })()`
103+ async function bundleCode ( ) {
104+ const bundle = await rollup ( {
105+ input : 'src/plausible.js' ,
106+ } )
107+
108+ const { output } = await bundle . generate ( {
109+ format : 'esm' ,
110+ } )
111+
112+ return output [ 0 ] . code
101113}
102114
103115function minify ( baseCode , globals ) {
0 commit comments