使用 Node.js 和 Shopify 集成的 Vite React 应用程序中的 HMR 问题

问题描述 投票:0回答:2

我目前正在使用 React(使用 Vite)和 Node.js 配置 Shopify 应用程序。但是,我遇到了热模块更换 (HMR) 的问题。

我的vite.config.js文件如下:

import path, { dirname } from 'node:path';

import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import sassDts from 'vite-plugin-sass-dts';
import react from '@vitejs/plugin-react';

const proxyOptions = {
    target: `http://127.0.0.1:${process.env.WEB_PORT}`,
    changeOrigin: false,
    secure: true,
    ws: false,
};

const host = process.env.HOST ? process.env.HOST.replace(/https?:\/\//, '') : 'localhost';

let hmrConfig;

if (host === 'localhost') {
    hmrConfig = {
        protocol: 'ws',
        host: 'localhost',
        port: 64999,
        clientPort: 64999,
    };
} else {
    hmrConfig = {
        protocol: 'wss',
        host: host,
        port: process.env.FRONTEND_PORT,
        clientPort: 443,
    };
}

export default defineConfig({
    root: dirname(fileURLToPath(import.meta.url)),
    plugins: [react(), tsconfigPaths(), sassDts()],

    resolve: { preserveSymlinks: true, alias: { '@/styles': path.join(__dirname, 'src', 'styles') } },

    server: {
        host: 'localhost',
        port: process.env.FRONTEND_PORT,
        hmr: hmrConfig,
        proxy: {
            '^/(\\?.*)?$': proxyOptions,
            '^/api(/|(\\?.*)?$)': proxyOptions,
        },
    },
});

当我将

proxyOptions
添加到服务器配置时,问题就出现了。添加后,HMR 无法按预期运行。我只能在手动刷新网页后才能看到我的 React 组件的变化。

相反,当我从服务器配置中删除

proxyOptions
时,HMR 可以正常工作。

我已经验证

process.env.WEB_PORT
对应于我的服务器正在侦听的端口。

任何在使用

proxyOptions
时解决 HMR 问题的见解或解决方案将不胜感激。

@shopify/app": "3.46.5
,

vite shopify-app hmr
2个回答
2
投票

我通过将

proxyOptions.ws
更改为 true

解决了这个问题

1
投票

我通过将 proxyOptions.ws 更改为 true 解决了这个问题

© www.soinside.com 2019 - 2024. All rights reserved.