如何在vite.config.ts中为IIFE格式输出指定自定义ID及属性
给Vite打包生成的script标签添加自定义属性/ID
要实现给dist目录下index.html中的script标签添加自定义ID或属性,你可以利用Vite提供的transformIndexHtml钩子,在构建流程中直接修改生成的HTML内容。
方法一:直接在vite.config.ts中配置transformIndexHtml
修改你的vite.config.ts,添加transformIndexHtml选项,通过字符串替换匹配并修改目标script标签:
import { defineConfig } from "vite" import react from "@vitejs/plugin-react-swc" export default defineConfig({ plugins: [react()], server: { port: Number(process.env.PORT) || 3000 }, build: { rollupOptions: { output: { format: "iife", name: "foo", assetFileNames: "[name][extname]", entryFileNames: "foo.js", chunkFileNames: "foo.js", extend: true, sourcemap: false } } }, // 添加HTML转换钩子 transformIndexHtml: { transform(html) { // 匹配目标script标签,插入自定义属性 return html.replace( /<script type="module" crossorigin src="\/foo.js">/, '<script id="my-custom-id" type="module" crossorigin src="/foo.js" data-foo="one" data-bar="two">' ) } } })
方法二:用Vite插件实现更灵活的修改
如果需要适配不固定的文件名或批量修改script标签,可以写成插件形式,借助HTML解析工具精准操作DOM:
import { defineConfig } from "vite" import react from "@vitejs/plugin-react-swc" import { parse, serialize } from 'node-html-parser' export default defineConfig({ plugins: [ react(), // 自定义插件处理script标签 { name: 'modify-script-tag', transformIndexHtml(html) { const root = parse(html) // 匹配所有src包含foo.js的script标签 const scriptTags = root.querySelectorAll('script[src*="foo.js"]') scriptTags.forEach(tag => { tag.setAttribute('id', 'my-custom-id') tag.setAttribute('data-foo', 'one') tag.setAttribute('data-bar', 'two') }) return serialize(root) } } ], server: { port: Number(process.env.PORT) || 3000 }, build: { rollupOptions: { output: { format: "iife", name: "foo", assetFileNames: "[name][extname]", entryFileNames: "foo.js", chunkFileNames: "foo.js", extend: true, sourcemap: false } } } })
使用该方法需要先安装依赖:
npm install node-html-parser --save-dev
额外提示
你当前配置了output.format: "iife"但生成的script标签仍为type="module",这是因为Vite默认会将产物处理为ES模块。如果要让script标签适配IIFE格式(移除module类型),可以在build配置中添加module: false:
build: { module: false, // 禁用ES模块输出 rollupOptions: { // 保留原有配置 } }
修改后生成的script标签会变为:
<script id="my-custom-id" src="/foo.js" data-foo="one" data-bar="two"></script>
内容的提问来源于stack exchange,提问作者diegosasw
相关产品推荐
相关产品推荐

