赞
踩
场景:vite打包后,将dist包嵌入到PC客户端使用;
开发环境:vite4.0+vue3.2,node16.17.1,window 10;
因为不支持file协议,可以使用官方插件@vite/plugin-legacy;
在 vite.config.js 文件配置
export default defineConfig({
base: "./",
});
一般情况下,vite的目标浏览器需要支持原生支持 ES模块,当需要支持低版本浏览器时,需要做到向下兼容
使用 npm
npm install @@vite/plugin-legacy -D
使用 yarm
yarn add @vitejs/plugin-legacy -D
import legacy from "@vitejs/plugin-legacy";
export default defineConfig({
base: "./",
plugins: [
legacy({
//targets里可指定兼容到某一特定版本,默认为[ "defaults", "not IE 11"];
targets: ["chrome 80", "defaults", "not IE 11"],
}),
vue(),
],
build: {
// 默认是modules,更改这个会去输出兼容浏览器,根据实际情况修改
target: ["es2015", "chrome63"],
},
});
< script id=“vite-legacy-entry” src=“./assets/index-legacy-9289651b.js”></ script>
到此应该就没问题了,如果项目不报错了,检查下html结构,是否正常加载组件,如果没有,检查下路由文件配置的路由模式,将history模式改为hash;
脚本自动处理
为了省事,可以将index.html的处理过程,已js脚本实现,避免手动修改导致的人为错误
安装fs
npm install fs
let fs = require("fs");
console.time("转换耗时");
const distPath = "./dist/index.html"; //打包路径的index.html
let htmlText = fs.readFileSync(distPath, "utf8");
let resultText = "";
let htmlArr = htmlText.match(/.*\n/g) || [];
htmlArr.forEach((str) => {
str = str.replace(/\s?nomodule\s?/g, " ");
str = str.replace(/\s?crossorigin\s?/g, " ");
str = str.replace(/data-src/g, "src");
if (!/type="module"/i.test(str)) resultText += str;
});
fs.writeFileSync(distPath, resultText, "utf8");
console.timeEnd("转换耗时");
node transform.js
检查编译后的dist文件夹内,index.html的内容是否修改成功,发开index.html到浏览器检查是否正常
然后修改package.json文件,在打包后执行这个脚本,这样每次打包就不用再手动修改了;
"scripts": {
"build": "vite build && node transform.js",
},
这里要注意脚本文件的位置
到这里不放心,可以执行 npm run build 打包命令,检查是否正常
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。