Skip to content

Commit

Permalink
Vite plugin to replace env vars in index.html (#8929)
Browse files Browse the repository at this point in the history
Vite's built-in support for replacing environment variables in
index.html has some issues. Especially with the way we handle
environment variables. This works around those issues by implementing
the replacement ourselves as a Vite plugin

See also #8928
  • Loading branch information
Tobbe authored and jtoar committed Jul 19, 2023
1 parent c075c32 commit 59389ca
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions packages/vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,5 +209,44 @@ export default function redwoodPluginVite(): PluginOption[] {
}),
},
}),
{
name: 'redwood-plugin-vite-html-env',

// Vite can support replacing environment variables in index.html but
// there are currently two issues with that:
// 1. It requires the environment variables to be exposed on
// `import.meta.env`, but we expose them on `process.env` in Redwood.
// 2. There's an open issue on Vite where it adds extra quotes around
// the replaced values, which breaks trying to use environment
// variables in src attributes for example.
// Until those issues are resolved, we'll do the replacement ourselves
// instead using transformIndexHtml. Doing it this was was also the
// recommended way until Vite added built-in support for it.
//
// Extra quotes issue: https://github.com/vitejs/vite/issues/13424
// transformIndexHtml being the recommended way:
// https://github.com/vitejs/vite/issues/3105#issuecomment-1059975023
transformIndexHtml: {
// Setting order: 'pre' so that it runs before the built-in
// html env replacement.
order: 'pre',
handler: (html: string) => {
let newHtml = html

rwConfig.web.includeEnvironmentVariables.map((envName) => {
newHtml = newHtml.replaceAll(
`%${envName}%`,
process.env[envName] || ''
)
})

Object.entries(process.env).forEach(([envName, value]) => {
newHtml = newHtml.replaceAll(`%${envName}%`, value || '')
})

return newHtml
},
},
},
]
}

0 comments on commit 59389ca

Please sign in to comment.