WebView 使用静态网页
Webview 使用静态网页
https://github.com/crper/vscode-webview-vite-vue-boilerplate/tree/main
如何打包所有文件到一个index.js 和 index.css
css和js需要打包成单独文件
// path: webview-ui/vite.config.ts
build: {
modulePreload: false, // 关闭预加载
outDir: "build", // 打包输出目录
emptyOutDir: true, // 打包之前清空build 文件夹
assetsInlineLimit: 99999999999, // 默认是4096
rollupOptions: {
output: {
entryFileNames: assets/[name].js, // 打包后的入口文件
chunkFileNames: assets/[name].js,
assetFileNames: assets/[name].[ext],
manualChunks: (id: string) => { // 打包后的静态资源,自定义策略,全部合并到 index
return 'index'
}
},
},
},
png这类静态图片直接打包成base64(参考上面的 assetsInlineLimit)
svg 用 vite-svg-loader, 默认转换为 Component
// path: webview-ui/vite.config.ts
svgLoader({ defaultImport: 'component' }),
// 在使用层面可以通过 query(?) 来转换 svg 为内联或者其他
// 具体可以去看这个插件的介绍,挺强大的
路由模式
因为内嵌 webview 不像浏览器有路由导航栏这些,一般 webview 没有前进后退的概念,这种我们的路由跳转优先采用内存路由(memory router), 它非常适合需要完全控制历史堆栈的场景, 类似 Vue 或者 React 都有提供!!
使用 vite-plugin-singlefile
参考:https://zhuanlan.zhihu.com/p/655080477
安装插件 pnpm i vite-plugin-singlefile 通过将内容都打包在 index.html,所以 index.html无依赖其他文件单独就可运行
配置 vite.config.js
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import { viteSingleFile } from 'vite-plugin-singlefile';
export default defineConfig({
plugins: [
vue(),
viteSingleFile(),
],
build: {
minify: false,
},
})
路由设置
history: createWebHashHistory("/") // 这里必须使用 hash
测试
通过 pnpm build 并在浏览器中
使用 vitejs/plugin-legacy
https://chuna2.787528.xyz/ztn195/p/19415855
pnpm i @vitejs/plugin-legacy
这是因为 现代浏览器的安全策略 限制了从 file:// 协议加载 ES 模块类型的资源。当你直接打开 HTML 文件时,浏览器将请求视为来自 null origin,而 CORS 策略不允许这种跨源请求。
解决方案参考:这篇文章:解决vite打包的项目不能直接用浏览器运行HTML文件
2.配置vite.config.ts(没有就找vite.config.js)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
plugins: [
vue(),
legacy({
targets:["defaults","not IE 11"],
})
],
base: './',
})
vite默认根目录"/",file://…访问需要基于index.html的路径,将base修改为./解决文件路径不对问题。由于vite打包的项目涉及跨域,引入legacy可以解决file://…没有跨域的定义的问题。
3.配置路由
history: createWebHashHistory(),
修改路由为hash模式(小编就是因为没有选择hash模式浪费了不少时间),因为hash模式不会走服务器,而是在本地直接处理。
4.修改打包后的index.html文件
将index.html中所有的 标签中的 type="module"、crossorigin、nomodule 删除,data-src 属性换成 src。
也可以写一个node脚本来处理
(1)安装 fs
npm add fs
(2)在项目根目录下新建html.js文件,写入下面代码
// 如果运行报错 Cannot use import statement outside a module 换成
//const fs = require("fs");
import fs from "fs";
const htmlPath = "./dist/index.html"; // 打包后的html文件路径
const htmlText = fs.readFileSync(htmlPath, 'utf8');
const htmlArr = htmlText.match(/.*\n/g) || [];
let result = "";
htmlArr.forEach(v => {
v = v
.replace(/script ?nomodule\s?/g, "script ")
.replace(/\s?crossorigin\s?/g, " ")
.replace(/data-src/g, 'src');
if (!v.includes(script type="module")) {
result += v;
}
});
fs.writeFileSync(htmlPath, result, 'utf8');
console.log("处理完成");
直接点击运行此文件就好了。
posted on 2026-01-11 14:16 tommao9925 阅读(7) 评论(0) 收藏 举报
浙公网安备 33010602011771号