Unlock seamless workflows and faster delivery with our latest releases- get the details

Adding a script tag to index.html to avoid stale js bundle and integrate with import-meta-env tooling

1 replies
Last updated: Feb 7, 2023
Is there a way to append a script tag to the index.html?I tried writing my own little vite plugin to
transform the html , but it doesn't seem to be running?
I would like to add a piece of code directly to the index.html, so I don't risk having it get stale with the js bundle.

Perhaps there is a better way to do that, but I also didn't have luck with adding a script to the
static
dir either.
My goal is to integrate with
import-meta-env tooling to allow for runtime env vars while self hosting.
Feb 2, 2023, 1:39 AM
In case anyone deals with this in the future, i ended up writing a custom rollup plugin that wrote the script to the head of the
index.html
that the sanity cli created:
// sanity.cli.ts
const importMetaEnvSpecialExpression = (options?: {
  out: string
}): PluginOption => {
  const out = options?.out ?? "dist"
  return {
    name: "build end",
    enforce: "post",
    async writeBundle(opts, things) {
      const html =
        things["index.html"].type === "asset" ? things["index.html"] : null
      if (!html || typeof html.source !== "string") return
      const parsedHtml = parse(html.source)
      const importMetaEnvSpecialScript = `<script>globalThis.import_meta_env = JSON.parse('"import_meta_env_placeholder"');</script>`
      parsedHtml
        .querySelector("head")
        ?.insertAdjacentHTML("afterbegin", importMetaEnvSpecialScript)

      await fs.writeFile(
        path.resolve(process.cwd(), out, "index.html"),
        parsedHtml.toString()
      )
    },
  }
}

export default defineCliConfig({
  // config options
    vite: (viteConfig: UserConfig): UserConfig => ({
    ...viteConfig,
    plugins: [
      ...(viteConfig.plugins ?? []),
      // plugin i was trying to integrate with
      ImportMetaEnvPlugin.vite({
        example: ".env.example.public",
      }),
      // custom plugin from above
      importMetaEnvSpecialExpression(),
    ],
  }),
})
Feb 7, 2023, 7:51 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?