我写了简单的todo-app,我正在尝试将它部署到Heroku。我之前部署在heroku上,我使用了Express + React。在我的server.js文件中,有一段代码:
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
如果应用程序正在生产中,那段代码将提供“build”文件夹,并且还会向每个请求发送“index.html”。
我需要类似的代码,但对于Koa + React。 Koa是非常简约的框架,所以我猜必须安装其他软件包,我不知道哪些。我尝试过koa-send和koa-static,但无法配置它们。我怎么做?
我现在无法测试它,但我认为它会是这样的:
const Koa = require('koa');
const Router = require('koa-router');
const send = require('koa-send');
const static = require('koa-static');
const app = new Koa();
const router = new Router();
if (process.env.NODE_ENV === 'production') {
app.use(static('./client/build'));
router.get('*', async (ctx, next) => {
try {
await send(ctx, './client/build/index.html');
} catch(err) {
// TODO: handle err?
return next();
}
});
}
app.listen(3000);