通常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");