React + Nunjucks Asset前端渲染

https://www.yuque.com/easy-team/egg-react/asset

${root}/app/controller/render.ts

  1. import { Controller, Context } from '@easy-team/res';
  2. export default class AdminController extends Controller {
  3. public async home(ctx: Context) {
  4. await ctx.renderAsset('asset.js', {
  5. title: 'React Asset Client Render',
  6. text: 'Egg + React + TypeScript + Webpack Client Side Render'
  7. }, { layout: path.join(ctx.app.baseDir, 'app/web/view/layout.tpl'),} );
  8. }
  9. }

${root}/app/web/view/layout.tpl

renderAsset 自动注入资源依赖对象,然后自己根据 asset 对象进行 CSS和 JS 注入到 HTML 页面。

<!DOCTYPE html>
<html lang='en'>
<head>
  <title>{{title}}</title>
  <meta name='keywords'>
  <meta name='description'>
  <meta http-equiv='content-type' content='text/html;charset=utf-8'>
  <meta name='viewport' content='initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui'>
  <link rel='shortcut icon' href='/favicon.ico' type='image/x-icon' />
  {% for item in asset.css %}
    <link rel="stylesheet" href='{{item}}' />
  {% endfor %}
</head>
<body>
  <div id='app'></div>
  <script type="text/javascript">
    window.__INITIAL_STATE__ = {{ asset.state | safe }};
  </script>
  {% for item in asset.js %}
    <script type="text/javascript" src="{{item}}"></script>
  {% endfor %}
</body>
</html>