Итак, я поиграл с различными комбинациями хапи + инерт, и это то, что мне помогло.
server.js
const Path = require('path');
const Hapi = require('hapi');
const Inert = require('inert');
const routes = require('./routes');
const init = async () => {
console.log('Routes are', routes);
const server = new Hapi.Server({
port: process.env.PORT || 5000,
routes: {
files: {
relativeTo: Path.join(__dirname, '../build')
}
}
});
await server.register(Inert);
server.route(routes);
/**
* This is required here because there are references to *.js and *.css in index.html,
* which will not be resolved if we don't match all remaining paths.
* To test it out, comment the code below and try hitting /login.
* Now that you know it doesn't work without the piece of code below,
* uncomment it.
*/
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: '.',
redirectToSlash: true,
index: true,
}
}
});
const options = {
ops: {
interval: 1000
},
reporters: {
myConsoleReporter: [
{
module: 'good-console',
args: [{ request: '*', response: '*' }]
},
'stdout'
]
}
};
await server.register({
plugin: require('good'),
options,
});
await server.start();
console.log('Server running at:', server.info.uri);
};
init();
/routes/index.js
/**
* Use this for all paths since we just need to resolve index.html for any given path.
* react-router will take over and show the relevant component.
*
* TODO: add a 404 handler for paths not defined in react-router
*/
const fileHandler = {
handler: (req, res) => {
console.log(res.file('index.html'));
return res.file('index.html');
}
}
const routes = [
{ method: 'GET', path: '/login', config: fileHandler },
]
module.exports = routes;
Ключевым моментом здесь является то, что для любого именованного пути (в данном случае /login
) мы всегда возвращаем файл index.html
.Для всех других путей мы говорим hapi возвращать файлы из нашего каталога build
, чтобы любые ссылки на файл *.css
или *.js
в нашем index.hml
были разрешены, и мы не столкнулись с 404.
Я не уверен, как react-router
принимает разрешение пути после загрузки index.html, но это выходит за рамки этого вопроса и, возможно, является предметом обсуждения в другой раз.
Что касается второго вопроса о горячей перезагрузке, я все еще пытаюсь понять это.На данный момент я работаю как с сервером hapi, так и с приложением Reaction-App независимо, так как мне нужно /api
для использования в приложении activ-app.Любые предложения или ответы приветствуются.