如何配置ViteJS生成不含type=module的script标签?
配置ViteJS控制dist中script标签生成形式
我使用ViteJS生成库文件及index.html,希望dist/index.html中生成最简形式的<script src="..."></script>标签,不包含type=module属性。但根目录的index.html中必须将script设置为type=module才能被ViteJS处理,因此需要通过Vite配置实现需求。
示例代码
- 根目录index.html:
... <body> <script type="module" src="/src/main.ts"></script> ... </body> ...
- 实际生成的dist/index.html:
... <head> <script type="module" crossorigin src="/assets/index-3ba57d45.js"></script> ... </head> ...
- 期望的dist/index.html:
... <head> <script src="/assets/index-3ba57d45.js"></script> ... </head> ...
解决方案
方法1:修改Build配置生成非ES模块格式
Vite默认生成ES模块脚本,会自动添加type=module属性。如果将输出格式改为IIFE或UMD,打包后的script标签会自动去掉type=module,同时脚本无需模块支持即可运行。
在vite.config.js(或.ts)中配置:
import { defineConfig } from 'vite'; export default defineConfig({ build: { lib: { entry: 'src/main.ts', name: 'YourLibraryName', // IIFE/UMD格式需指定全局变量名称 formats: ['iife'], // 可选值:'iife' / 'umd',按需选择 fileName: (format) => `index.${format}.js`, }, rollupOptions: { // 如有外部依赖,可通过external配置排除 // external: ['vue'], output: { // 对应lib.name,映射外部依赖的全局变量 // globals: { vue: 'Vue' } }, }, }, });
方法2:通过插件修改HTML中的Script标签
若仍需生成ES模块格式,仅需移除type=module和crossorigin属性,可自定义Vite插件在打包时修改HTML内容:
在vite.config.js中添加插件:
import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ { name: 'modify-html-script', transformIndexHtml(html) { // 替换目标script标签,移除多余属性 return html.replace(/<script type="module" crossorigin src="([^"]+)">/g, '<script src="$1">'); }, }, ], });
注意:方法2生成的脚本仍为ES模块,移除
type=module后可能不符合规范,部分旧浏览器可能无法正常运行,建议优先使用方法1。
内容的提问来源于stack exchange,提问作者Neekobus
相关产品推荐
相关产品推荐

