我目前正在使用 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
,
我通过将
proxyOptions.ws
更改为 true 解决了这个问题
我通过将 proxyOptions.ws 更改为 true 解决了这个问题