根据生成的构建方式,仅查看生成dist
目录中的文件可能还不够。例如,如果您使用 CRA,您可能需要更类似于他们在这篇文章中使用的东西来查找子目录中的所有有效路线。所以你可能有一些看起来像
import Koa from 'koa';
import serve from 'koa-static';
import fs from 'fs';
import path from 'path';
const app = new Koa();
const dist = path.join(__dirname, 'dist');
let validRoutes;
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
};
walk(dist, function(err, results) {
if (err) throw err;
validRoutes = results;
});
function isRouteValid (r: string) {
if (!validRoutes || !r) return false;
return validRoutes.find(route => r === route);
}
app.use(async (ctx, next) => {
if (!isRouteValid(path.resolve(dist, ctx.url.slice(1)))) ctx.path = 'index.html';
await next();
});
app.use(serve(dist));
app.listen(3010);