如何在 Koa 中提供构建文件夹?
How to serve build folder in Koa?
我已经编写了简单的待办事项应用程序,并且正在尝试将其部署到 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);
我已经编写了简单的待办事项应用程序,并且正在尝试将其部署到 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);