|
13 | 13 |
|
14 | 14 | ## csr模式下自己diy模版的生成内容 |
15 | 15 |
|
16 | | -借助React官方api我们可以将一个React组件编译为html字符串 |
| 16 | +借助React官方Api我们可以将一个React组件编译为html字符串 |
17 | 17 |
|
18 | 18 | ### 本地开发 |
19 | 19 |
|
|
23 | 23 |
|
24 | 24 | ``` js |
25 | 25 | // yk-cli/renderLayout.js |
26 | | -const Layout = require(cwd + '/web/layout').default |
27 | | - |
28 | | -const reactToString = (Component, props) => { |
29 | | - return renderToString(React.createElement(Component, props)) |
30 | | -} |
| 26 | +const renderLayout = async () => { |
| 27 | + let Layout |
| 28 | + // 我们调用webpack的api来用应用目录下的webpack配置来编译layout组件,使其可以在Node环境中运行 |
| 29 | + try { |
| 30 | + // serverless 场景我们从事先构建好的应用目录下的dist文件夹中读取layout |
| 31 | + Layout = isServerless ? require('../../../dist/Layout.server').default : require('../dist/Layout.server').default |
| 32 | + } catch (error) { |
| 33 | + // 非serverless场景首次读取失败我们先调用webpack api构建一遍在ykcli的目录下再读取 |
| 34 | + const webpackWithPromise = require('./util') |
| 35 | + await webpackWithPromise(serverConfig) |
| 36 | + Layout = require('../dist/Layout.server').default |
| 37 | + } |
31 | 38 |
|
32 | | -// 此时props.children的值为undefined,我们只需要渲染一个空的layout骨架即可 |
33 | | -const props = { |
34 | | - layoutData: { |
35 | | - app: { |
36 | | - config: config |
| 39 | + // 此时props.children 为 undefined 我们只需要传染一个空的layout骨架即可 |
| 40 | + const props = { |
| 41 | + layoutData: { |
| 42 | + app: { |
| 43 | + config: config |
| 44 | + } |
37 | 45 | } |
38 | 46 | } |
39 | | -} |
40 | | - |
41 | | -const string = reactToString(Layout, props) |
42 | 47 |
|
43 | | -module.exports = string |
| 48 | + const str = reactToString(Layout, props) |
| 49 | + return str |
| 50 | +} |
44 | 51 | ``` |
45 | 52 |
|
46 | 53 | 然后启动服务,将string返回 |
@@ -167,8 +174,9 @@ return stream |
167 | 174 | // ykfe-utils/renderToStream.js |
168 | 175 |
|
169 | 176 | if (config.type !== 'ssr') { |
170 | | - const string = require('yk-cli/bin/renderLayout') |
171 | | - return string |
| 177 | + const renderLayout = require('yk-cli/bin/renderLayout').default |
| 178 | + const str = await renderLayout() |
| 179 | + return str |
172 | 180 | } |
173 | 181 | ``` |
174 | 182 |
|
|
0 commit comments