Skip to content

Commit

Permalink
Export 'browser' object from global.vars.js to access esbuild's defin…
Browse files Browse the repository at this point in the history
…e field

This lets you define variable values at build time.
  • Loading branch information
bcomnes committed Jul 17, 2022
1 parent cb11e8c commit c1180df
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
15 changes: 11 additions & 4 deletions lib/build-js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,16 @@ export async function buildJs (src, dest, siteData, opts) {
if (page.clientBundle) entryPoints.push(join(src, page.clientBundle.relname))
}

const globalVars = JSON.stringify(await resolveVars(siteData?.globalVars?.filepath))
const browserVars = await resolveVars(siteData?.globalVars?.filepath, 'browser')

const define = {}

if (browserVars) {
for (const [k, v] of Object.entries(browserVars)) {
define[k] = JSON.stringify(v)
}
}

const buildOpts = {
entryPoints,
logLevel: 'silent',
Expand All @@ -30,9 +39,7 @@ export async function buildJs (src, dest, siteData, opts) {
target: [
'es2020'
],
define: {
globalVars
}
define
}

try {
Expand Down
4 changes: 2 additions & 2 deletions lib/build-pages/resolve-vars.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
* @param {[type]} varsPath [description]
* @return {[type]} [description]
*/
export async function resolveVars (varsPath) {
export async function resolveVars (varsPath, key = 'default') {
if (!varsPath) return {}

const { default: maybeVars } = await import(varsPath)
const { [key]: maybeVars } = await import(varsPath)

if (typeof maybeVars === 'function') return maybeVars()
return maybeVars
Expand Down

0 comments on commit c1180df

Please sign in to comment.