refactor: 提取widget初始化逻辑到单独模块并增加调试日志

This commit is contained in:
haorwen
2026-03-15 07:59:45 +08:00
committed by cnb
parent e23b2207b1
commit 0ad7764e3e
4 changed files with 26 additions and 21 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "vocechat-web",
"version": "0.9.64",
"version": "0.9.65",
"homepage": "https://voce.chat",
"dependencies": {
"@metamask/onboarding": "^1.0.1",
+3
View File
@@ -23,10 +23,13 @@ const getBaseOrigin = () => {
// 检查是否有 widget originShadow DOM 模式)
const widgetOrigin = (window as any).__VOCECHAT_WIDGET_ORIGIN__;
if (widgetOrigin) {
console.log('[Config] Using widget origin:', widgetOrigin);
return widgetOrigin;
}
console.log('[Config] Using location.origin:', location.origin);
return location.origin;
}
console.log('[Config] Using dev origin:', dev_origin);
return dev_origin;
};
+2 -20
View File
@@ -1,23 +1,5 @@
// 在 Shadow DOM 模式下,动态设置 webpack publicPath
// 这样 webpack 运行时加载的动态资源(如代码分割的 chunk)会从正确的源服务器加载
let widgetOrigin = '';
if (typeof document !== 'undefined') {
const currentScript = document.currentScript as HTMLScriptElement;
if (currentScript && currentScript.src) {
try {
const scriptUrl = new URL(currentScript.src);
// 获取脚本所在的目录路径(去掉文件名)
const scriptPath = scriptUrl.pathname.substring(0, scriptUrl.pathname.lastIndexOf('/') + 1);
// 设置为脚本所在的完整目录路径
__webpack_public_path__ = scriptUrl.origin + scriptPath;
// 保存 origin 供 i18n 使用
widgetOrigin = scriptUrl.origin;
(window as any).__VOCECHAT_WIDGET_ORIGIN__ = widgetOrigin;
} catch (e) {
console.warn('Failed to set webpack public path:', e);
}
}
}
// 必须首先导入初始化文件,设置 webpack publicPath 和 widget origin
import "./widget-init";
import ReactDOM from "react-dom/client";
import { Toaster } from "react-hot-toast";
+20
View File
@@ -0,0 +1,20 @@
// 这个文件必须在所有其他模块之前加载
// 在 Shadow DOM 模式下,动态设置 webpack 的 publicPath 和 widget origin
if (typeof document !== 'undefined') {
const currentScript = document.currentScript as HTMLScriptElement;
if (currentScript && currentScript.src) {
try {
const scriptUrl = new URL(currentScript.src);
// 获取脚本所在的目录路径(去掉文件名)
const scriptPath = scriptUrl.pathname.substring(0, scriptUrl.pathname.lastIndexOf('/') + 1);
// 设置为脚本所在的完整目录路径
__webpack_public_path__ = scriptUrl.origin + scriptPath;
// 保存 origin 供其他模块使用
(window as any).__VOCECHAT_WIDGET_ORIGIN__ = scriptUrl.origin;
console.log('[Widget Init] Set origin to:', scriptUrl.origin);
console.log('[Widget Init] Set publicPath to:', scriptUrl.origin + scriptPath);
} catch (e) {
console.warn('[Widget Init] Failed to set webpack public path:', e);
}
}
}