我遇到的问题是热重载正在尝试转到
localhost:8000/build
(正在使用应用程序构建的地方)
而不是
localhost:3000/build
,这是 webpack-dev-server 构建位置。
我尝试使用代理并为此花费了大量时间。这可以吗?这是我的 devServer 配置。
编辑:有些配置是不必要的,因为我尝试了很多东西。
Edit2:当 liveReload 为 true 时一切正常,但刷新页面会使开发太慢。
{
...,
devServer: {
allowedHosts: 'all',
static: {
directory: path.join(__dirname, 'build'),
watch: true,
},
port: process.env.LOCAL_PORT,
host: process.env.LOCAL_HOST,
compress: true,
client: {
logging: 'warn',
overlay: {
errors: false,
warnings: false,
runtimeErrors: true,
},
},
hot: 'only',
liveReload: false,
watchFiles: ['src/**/*'],
proxy: [
{
context: ['/build'],
target: 'http://localhost:3000',
},
],
},
}
我能够通过 chatGPT 解决这个问题。
事实证明代理不是在这里使用的正确选择,我必须配置很多东西,包括:
output
和
devServer.devMiddleware
的这就是我最终的工作成果。请注意,该项目最初是使用react-scripts启动的,因此在原始场景中可能需要一些额外的配置(当前未弹出)。
const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv');
module.exports = (env) => {
const envPath = path.resolve(__dirname, '.env');
const envVars = dotenv.config({ path: envPath }).parsed || {};
const localHost = process.env.LOCAL_HOST || 'localhost';
const localPort = process.env.LOCAL_PORT || 3000;
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
return {
entry: './src/exports/index.js',
output: {
filename: 'kindertales-ui.js',
path: path.resolve(__dirname, 'build'),
publicPath: `http://${localHost}:${localPort}/build/`,
},
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify(envVars),
}),
new ReactRefreshWebpackPlugin(),
],
module: { ... },
devServer: {
allowedHosts: 'all',
static: {
directory: path.join(__dirname, 'build'),
watch: true,
serveIndex: true,
},
headers: {
'Content-Type': 'application/javascript', // Ensure correct MIME type
'Access-Control-Allow-Origin': '*', // Allow all origins (you can restrict it to specific origins if needed)
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
port: process.env.LOCAL_PORT,
host: localHost,
compress: true,
client: {
logging: 'warn',
overlay: {
errors: false,
warnings: false,
runtimeErrors: true,
},
webSocketURL: {
hostname: localHost, // The hostname for the WebSocket
port: localPort, // The port for the WebSocket (matches your dev server)
protocol: 'ws', // Use 'wss' if you're using HTTPS
pathname: '/ws',
},
},
hot: true,
liveReload: false,
watchFiles: ['src/**/*'],
devMiddleware: {
publicPath: `http://${localHost}:${localPort}/build/`,
},
},
};
};