关于vite-plugin-monkey的启动实时更新的模式是如何实现的 #72
Replies: 2 comments 2 replies
-
你说的 以下是 vite-plugin-monkey 的原理的简单描述 vite 主要有两种工作模式, serve 和 build 在 build 模式下,使用 vite build 将你的项目打包成单个文件 build.user.js ,想要监听文件变化连续构建可以使用 vite build --watch 这种开发方式和你说的 而在 serve 模式下,你的代码始终以 esm 格式在浏览器运行,vite 也不会将你的代码打包成单个文件 如果是使用vite开发普通的web项目(不是油猴脚本项目),你的 index.html 一般是如下内容 <!DOCTYPE html>
<html lang="en">
<head>
<title>Vite + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html> 当你在 vite serve 下访问 index.html 时,vite 将 index.html 转换为以下内容 <!DOCTYPE html>
<html lang="en">
<head>
<script type="module" src="/@vite/client"></script>
<title>Vite + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html> 也就是 而当你使用 vite-plugin-monkey 时,在 vite serve 下油猴脚本安装的代码一般是如下内容 ;(({ entrySrc = `` }) => {
window.GM;
document.__monkeyWindow = window;
console.log(`[vite-plugin-monkey] mount monkeyWindow to document`);
const entryScript = document.createElement("script");
entryScript.type = "module";
entryScript.src = entrySrc;
document.head.insertBefore(entryScript, document.head.firstChild);
console.log(`[vite-plugin-monkey] mount entry module to document.head`);
})(...[
{
"entrySrc": "http://127.0.0.1:5173/__vite-plugin-monkey.entry.js"
}
]); 这个油猴脚本实际上只做了两件事
当访问 import "/@vite/client";
import "/src/main.ts"; 生成这个模块的具体代码是 vite-plugin-monkey/packages/vite-plugin-monkey/src/node/plugins/server.ts Lines 134 to 185 in 99839cc 也就是 这相当于使用 vite 开发普通 web 项目,只不过模块运行的环境和域名不一样 因此 vite 和其他插件在 web 项目里提供的 hmr 功能也能照常运行 hmr(热更新) 是由 vite 和其他插件提供的,不是 vite-plugin-monkey 提供的, vite-plugin-monkey 只是将模块入口放到了 脚本宿主域名下 |
Beta Was this translation helpful? Give feedback.
-
我使用 @require file 的方式没遇到缓存, 而且这个很关键, 我就是通过这个来绕过 CSP 的 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
因为之前一直都是用的大佬的脚手架搭建的项目,当我项目启动以后默认就会打包浏览器加载脚本实时更新。很方便。
但是我昨天在搞一个github的项目,集成了插件和脚本,因为使用的是deno+preact,关于脚本启动我不太清楚,但是是通过启动以后也是把dist目录下面的user.js手动复制到脚本里面,但是是通过
// @require file://E:\daimaxiangmu\vscode\sourceCode\next-translator/dist/userscript/b.user.js
(踩坑,必须设置油猴允许访问本地文件,同时通过启动server(require url地址)这种情况做不到实时更新,好像是require有缓存。同时还遇到了这个项目脚本启动请求跨域,还没有解决
来实现的,所以我好奇大佬的脚手架这块是如何设计的,似乎你那个就不需要。
Beta Was this translation helpful? Give feedback.
All reactions