You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CLI参数动态设置Vite Dev中index.html的script src属性?

实现动态指定Canvas动画文件的Vite配置方案

当然可以实现,通过自定义Vite插件和调整命令参数传递逻辑就能达成需求,具体步骤如下:

步骤1:调整package.json的dev命令

修改scripts里的dev命令,确保CLI参数能正确传递给Vite:

{
  "scripts": {
    "dev": "vite --"
  }
}

这样执行npm run dev animation1时,animation1会作为自定义参数传递给Vite进程。

步骤2:编写Vite自定义插件修改index.html

在vite.config.ts中添加一个插件,利用Vite的transformIndexHtml钩子动态替换script标签的src属性:

import { defineConfig } from 'vite';
import fs from 'fs/promises';
import path from 'path';

export default defineConfig({
  plugins: [
    {
      name: 'dynamic-animation-loader',
      async transformIndexHtml(html) {
        // 获取CLI传入的自定义参数(跳过node、vite命令本身的参数)
        const args = process.argv.slice(3);
        // 动画文件名,默认使用animation1
        let animationName = args[0] || 'animation1';

        // 可选:校验动画文件是否存在,避免加载不存在的文件
        const animationPath = path.resolve(__dirname, `animations/${animationName}.js`);
        try {
          await fs.access(animationPath);
        } catch {
          console.warn(`动画文件 ${animationName}.js 不存在,将使用默认的 animation1.js`);
          animationName = 'animation1';
        }

        // 替换index.html中的script src属性
        return html.replace(
          /src="\.\.\/animations\/.*?\.js"/,
          `src="../animations/${animationName}.js"`
        );
      }
    }
  ]
});

步骤3:验证效果

  • 执行npm run dev:默认加载animation1.js,与原有逻辑一致。
  • 执行npm run dev animation2:index.html中的script标签会被自动替换为src="../animations/animation2.js",浏览器将展示对应的动画。

内容的提问来源于stack exchange,提问作者pinkboid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:27:12