JSPM

vite-plugin-html-public-path

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 4
  • Score
    100M100P100Q75292F
  • License ISC

Implement dynamic public path in index.html

Package Exports

  • vite-plugin-html-public-path
  • vite-plugin-html-public-path/dist/index.es.js
  • vite-plugin-html-public-path/dist/index.umd.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (vite-plugin-html-public-path) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

vite-plugin-html-public-path

Implement dynamic public path in index.html

Why need the plugin?

Sometime, we need to set the public path dynamically, for example, when we use vite to build the project, we need to set the public path according to the environment. but, we can't set the public path in the index.html file, so we need to use this plugin to transform all static link/script tags to dynamic tags

alt text

Install

pnpm install vite-plugin-html-public-path -D

Usage

you can use initialPrefixScript to return the public path of the application.

import { defineConfig } from 'vite'
import htmlPublicPath from 'vite-plugin-html-public-path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    htmlPublicPath({
      // it will be injected to head of script tag
      initialPrefixScript: `
        const prefix = window.__PREFIX__ = "/customPrefix";
        return prefix;
      `
    })
  ],
})

with async case, you can use await in initialPrefixScript

import { defineConfig } from 'vite'
import htmlPublicPath from 'vite-plugin-html-public-path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    htmlPublicPath({
      initialPrefixScript: `
        const prefix = await new Promise((resolve) => {
          setTimeout(() => {
            resolve("/customPrefix");
          }, 1000);
        });
        return prefix;
      `
    })
  ],
})

Options

initialPrefixScript

  • type: string
  • default: ""

provide runtime code to get the public path of the application. It will be injected to head of script tag. support async and await.