首页 > 解决方案 > HapiJS + create-react-app + webpack-dev-middleware 配置

问题描述

我目前正在使用create-react-app带有 HapiJS 作为代理来提供静态文件。

这是我当前设置的样子:

//server.js
const server = new Hapi.Server({
        port: process.env.PORT || 80,
        routes: {
            files: {
                relativeTo: Path.join(__dirname, '../build')
            }
        }
    });
await server.register(Inert);
server.route(routes); // comes from an array of routes defined in react-routes.js
await server.start();
console.log('Server running at:', server.info.uri);
//react-routes.js
//All the routes mapped here should return an index.html file.
//React will take care of routing.
const routes = [
    { method: 'GET', path: '/home', config: fileHandler }
    { method: 'GET', path: '/account', config: fileHandler }
    ]

const fileHandler = {
    handler: (req, res) => {
        return res.file('index.html');
    }
}

nodemon在开发中使用来运行服务器并react-scripts start运行 react-app。现在的问题是,HapiJS 服务器只提供build使用react-scripts build. 我知道为了连接到 webpack 构建,我需要为 HapiJS 使用中间件。

查看webpack 文档,我发现它需要对webpack.config.js文件的引用。但我不能随意使用ejectwebpack.config.js根据需要访问。

所以问题是:

注意:这不是服务器端渲染,我使用 HapiJS 作为代理,因为涉及跨域 API 调用,代理帮助我避免臭名昭著的 CORS 错误并为应用程序提供服务。

标签: reactjswebpackcreate-react-apphapijswebpack-dev-middleware

解决方案


推荐阅读