Skip to content

Commit

Permalink
fix(ssr): OOM when dev rendering (umijs#6157)
Browse files Browse the repository at this point in the history
* fix(ssr): dev render OOM

* fix: clear cache

* chore: style

* chore: reset yarn.lock

* fix: isDev
  • Loading branch information
ycjcl868 authored Feb 23, 2021
1 parent 988be39 commit 4052ef6
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 43 deletions.
11 changes: 0 additions & 11 deletions examples/ssr-koa/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ const mount = require('koa-mount');
const { join, extname } = require('path');
const { parseCookie, parseNavLang } = require('./serverHelper');

const isDev = process.env.NODE_ENV === 'development';

const root = join(__dirname, 'dist');

const app = new Koa();
Expand Down Expand Up @@ -52,15 +50,6 @@ app.use(async (ctx, next) => {
console.log('----------------服务端报错-------------------', error);
ctx.throw(500, error);
}
/**
* 这里fix了由于没有使用内部server而造成的缓存问题,
* 原因是require会带有缓存,在修改代码以后会不更新
* 这里判断的环境变量,如果是dev环境,自动删除require
* 缓存
*/
if (isDev) {
delete require.cache[require.resolve('./dist/umi.server')];
}
ctx.body = html;
} else {
await next();
Expand Down
11 changes: 0 additions & 11 deletions examples/ssr-with-eggjs/app/controller/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,6 @@ class HomeController extends Controller {
global.href = ctx.request.href;
global._cookies = ctx.helper.parseCookie(ctx);
global._navigatorLang = ctx.helper.parseNavLang(ctx);
/**
* 这里可以根据自己的环境配置修改,
* 规则就是开发环境需要删除require缓存
* 重新load文件
*
*/

const isDev = app.config.env != 'prod';
if (isDev) {
delete require.cache[require.resolve('../public/umi.server')];
}

// 先走 eggjs 的v iew 渲染
const htmlTemplate = await ctx.view.render('index.html');
Expand Down
31 changes: 22 additions & 9 deletions packages/preset-built-in/src/plugins/features/ssr/ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import serialize from 'serialize-javascript';
import { performance } from 'perf_hooks';
import { Route } from '@umijs/core';
import { IApi, BundlerConfigType } from '@umijs/types';
import { winPath, Mustache, lodash as _, routeToChunkName } from '@umijs/utils';
import {
winPath,
Mustache,
lodash as _,
routeToChunkName,
cleanRequireCache,
} from '@umijs/utils';
import { matchRoutes, RouteConfig } from 'react-router-config';
import { webpack } from '@umijs/bundler-webpack';
import ServerTypePlugin from './serverTypePlugin';
Expand Down Expand Up @@ -230,10 +236,21 @@ export default (api: IApi) => {
return config;
});

// make sure to clear umi.server.js cache
api.onDevCompileDone(() => {
const serverExp = new RegExp(_.escapeRegExp(OUTPUT_SERVER_FILENAME));
// clear require cache
for (const moduleId of Object.keys(require.cache)) {
if (serverExp.test(moduleId)) {
cleanRequireCache(moduleId);
}
}
});

// modify devServer content
api.modifyDevHTMLContent(async (defaultHtml, { req }) => {
// umi dev to enable server side render by default
const { stream, devServerRender = true } = api.config?.ssr || {};
const { mode, devServerRender = true } = api.config?.ssr || {};
const serverPath = path.join(
api.paths.absOutputPath!,
OUTPUT_SERVER_FILENAME,
Expand All @@ -245,7 +262,7 @@ export default (api: IApi) => {

try {
const startTime = performance.nodeTiming.duration;
const render = require(serverPath);
let render = require(serverPath);
const context = {};
const { html, error } = await render({
origin: `${req.protocol}://${req.get('host')}`,
Expand All @@ -257,18 +274,14 @@ export default (api: IApi) => {
});
const endTime = performance.nodeTiming.duration;
console.log(
`[SSR] ${stream ? 'stream' : ''} render ${req.url} start: ${(
`[SSR] ${mode === 'stream' ? 'stream' : ''} render ${req.url} start: ${(
endTime - startTime
).toFixed(2)}ms`,
);
if (error) {
throw error;
}
// if dev clear cache, OOM
if (require.cache[serverPath]) {
// replace default html
delete require.cache[serverPath];
}
render = null;
return html;
} catch (e) {
api.logger.error('[SSR]', e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import './pluginRegister';
// https://github.com/webpack/webpack/issues/4175#issuecomment-342931035
const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;

let routes;

/**
* server render function
* @param params
Expand Down Expand Up @@ -71,16 +69,14 @@ const render: IServerRender = async (params) => {
* routes init and patch only once
* beforeRenderServer must before routes init avoding require error
*/
if (!routes) {
// 主要为后面支持按需服务端渲染,单独用 routes 会全编译
routes = {{{ Routes }}};
// allow user to extend routes
plugin.applyPlugins({
key: 'patchRoutes',
type: ApplyPluginsType.event,
args: { routes },
});
}
// 主要为后面支持按需服务端渲染,单独用 routes 会全编译
const routes = {{{ Routes }}};
// allow user to extend routes
plugin.applyPlugins({
key: 'patchRoutes',
type: ApplyPluginsType.event,
args: { routes },
});

// for renderServer
const opts = {
Expand Down

0 comments on commit 4052ef6

Please sign in to comment.