html.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Plugin to minimize and use ejs template syntax in index.html.
  3. * https://github.com/anncwb/vite-plugin-html
  4. */
  5. import type { PluginOption } from 'vite'
  6. import { createHtmlPlugin } from 'vite-plugin-html'
  7. import pkg from '../../../package.json'
  8. import { GLOB_CONFIG_FILE_NAME } from '../../constant'
  9. export function configHtmlPlugin(env: ViteEnv, isBuild: boolean) {
  10. const { VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = env
  11. const path = VITE_PUBLIC_PATH.endsWith('/') ? VITE_PUBLIC_PATH : `${VITE_PUBLIC_PATH}/`
  12. const getAppConfigSrc = () => {
  13. return `${path || '/'}${GLOB_CONFIG_FILE_NAME}?v=${pkg.version}-${new Date().getTime()}`
  14. }
  15. // 当执行 yarn build 构建项目之后,会自动生成 _app.config.js 文件并插入 index.html
  16. // _app.config.js 用于项目在打包后,需要动态修改配置的需求,如接口地址
  17. // 不用重新进行打包,可在打包后修改 /dist/_app.config.js 内的变量,刷新即可更新代码内的局部变量
  18. const htmlPlugin: PluginOption[] = createHtmlPlugin({
  19. minify: isBuild,
  20. inject: {
  21. // Inject data into ejs template
  22. // 需要注入 index.html ejs 模版的数据 使用在 html 中 :<div><%= title %></div>
  23. data: {
  24. title: VITE_GLOB_APP_TITLE,
  25. },
  26. // Embed the generated app.config.js file 需要注入的标签列表
  27. tags: isBuild
  28. ? [
  29. {
  30. tag: 'script',
  31. attrs: {
  32. src: getAppConfigSrc(),
  33. },
  34. },
  35. ]
  36. : [],
  37. },
  38. })
  39. return htmlPlugin
  40. }