描述:
我最近将我的 React TypeScript 项目从 Create React App (CRA) with Webpack 迁移到了 Vite。虽然开发体验有所改善,但我遇到了应用程序初始加载时间的问题,特别是在另一个网站的 iframe 中托管时。
当页面加载缓慢时就会出现问题,导致我的应用程序错过托管网站发送的
postMessage
。我已经使用 addEventListener('message', ...)
设置了事件侦听器,但由于初始加载延迟,因此未捕获消息。
附加信息:
我已确保
message
的事件侦听器设置正确。
该问题似乎与托管在 iframe 中时初始加载时间较慢有关。
问题:
是否有推荐的方法来优化 Vite 项目的初始加载时间,特别是在 iframe 中托管时?另外,有没有策略保证加载过程中不会错过
postMessage
事件?
项目配置:
反应
打字稿
Vite
我的vite.config.ts:
import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv } from 'vite';
import mkcert from 'vite-plugin-mkcert';
import svgr from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';
import fixReactVirtualized from 'esbuild-plugin-react-virtualized';
import envCompatible from 'vite-plugin-env-compatible';
const hostAppName = undefined;
export default defineConfig(({ mode }) => {
return {
envPrefix: 'REACT_APP_',
base: '/',
plugins: [
react(),
envCompatible(),
tsconfigPaths(),
svgr({}),
mkcert(),
],
optimizeDeps: {
esbuildOptions: {
plugins: [fixReactVirtualized],
},
},
server: {
host: hostAppName,
port: 3000,
open: true,
},
preview: {
port: 8080,
},
build: {
outDir: 'build',
modulePreload: false,
target: 'esnext',
minify: false,
cssCodeSplit: false,
sourcemap: true,
rollupOptions: {
onwarn(warning, defaultHandler) {
if (warning.code === 'SOURCEMAP_ERROR') {
return;
}
defaultHandler(warning);
},
},
},
};
});
我尝试过的:
将项目从 Create React App (CRA) with Webpack 迁移到 Vite。
探索Vite配置以优化初始加载时间。
已验证
postMessage
的事件侦听器是否已正确设置。
实施了各种配置来解决该问题,包括使用
mkcert
、svgr
等插件。
任何见解或建议将不胜感激。谢谢!
对于您的Vite项目,初始加载时间可能会受到多种因素的影响,包括但不限于JavaScript包的大小、发出的网络请求数量以及代码拆分的效率。
使用Vite的内置可视化工具来分析您的包大小并识别大的依赖项。
import { visualizer } from 'rollup-plugin-visualizer';
// Add to your plugins array in vite.config.ts
plugins: [
react(),
// Other plugins
visualizer(),
],
确保您正在利用动态导入来延迟加载不是立即需要的组件和模块。
const LazyComponent = React.lazy(() => import('./LazyComponent'));
其他建议包括:
<link rel="preload">
和 <link rel="prefetch">
以便更早或在空闲时间加载它们。为了解决由于加载缓慢而丢失
postMessage
事件的问题,请考虑为传入消息实现队列系统。这意味着如果应用程序尚未准备好处理接收到的消息,则将其存储在队列中,然后在完全加载后处理它们。let isAppReady = false;
const messageQueue = [];
window.addEventListener('message', event => {
if (!isAppReady) {
messageQueue.push(event);
} else {
// Process the message
}
});
应用程序准备就绪后,处理存储在队列中的消息。
function processQueuedMessages() {
while (messageQueue.length > 0) {
const event = messageQueue.shift();
// Process the message
}
}
// Call this function when your app is initialized
isAppReady = true;
processQueuedMessages();