让 VIte+Vue3 打包的项目,在本地可以双击 index.html 打开运行

本文介绍了如何在本地使用Vite.js和plugin-legacy插件,配合JSDOM库,将Vue3打包项目转换为能在浏览器直接运行的HTML文件,移除`nomodule`和`crossorigin`属性,以及替换`data-src`为`src`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通常Vue3打包的项目只能放在web服务器里面,用 http://服务器地址 的方式运行,双击 index.html 是无法运行的。

如果要在本地运行,可以按照下面的步骤来实现。

首先,安装@vitejs/plugin-legacy:
npm i @vitejs/plugin-legacy --save

然后打开vite.config.js文件,加入如下配置:

import legacy from '@vitejs/plugin-legacy';

export default defineConfig({
  base:"./",
  plugins:[
    vue(),
    legacy({
      targets:["defaults","not IE 11"],
    })
  ]
});

如果你的base不是 ./ ,那么在项目打包完成后,最好运行下面的 nodejs 脚本:

import fs from 'fs';
import {JSDOM} from 'jsdom';

const dom = new JSDOM(fs.readFileSync("./dist/index.html"));

var tags = dom.window.document.querySelectorAll("*[type=\"module\"]");
var baseSrc = tags[0].src;
console.log(baseSrc);
var index = baseSrc.indexOf("/assets/");
baseSrc = baseSrc.substr(0,index+1);
console.log(baseSrc);

var script1 = dom.window.document.querySelector("#vite-legacy-polyfill");
script1.setAttribute("src" ,baseSrc + script1.getAttribute("src") );

script1 = dom.window.document.querySelector("#vite-legacy-entry");
script1.setAttribute("data-src" ,baseSrc + script1.getAttribute("data-src") );


var html = "<!DOCTYPE html>\r\n" + dom.window.document.documentElement.outerHTML;
fs.writeFileSync("./dist/index.html", html);
console.log("成功修改dist/index.html");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值