Bez popisu

template.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* eslint-disable no-use-before-define */
  2. // 待渲染完整的页面
  3. // 这里的页面建议以最简形式,如果需要复杂的头设定使用react-helmet组件
  4. /**
  5. * @function 生成同构直出的HTML界面模板
  6. * @param html
  7. * @param initialState
  8. * @param scripts
  9. * @param styles
  10. * @return {string}
  11. */
  12. export default (html, initialState = {}, scripts = [], styles = []) => {
  13. return `
  14. <!doctype html>
  15. <html>
  16. <head>
  17. <meta charset="utf-8">
  18. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  19. ${styleMapper(styles)}
  20. </head>
  21. <body>
  22. <div id="root">${html}</div>
  23. </body>
  24. <script>
  25. window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
  26. </script>
  27. ${scriptMapper(scripts)}
  28. </html>
  29. `;
  30. };
  31. /**
  32. * @function 将输入的样式文件路径转化为Link标签
  33. * @param styles
  34. * @return {*}
  35. */
  36. const styleMapper = styles => {
  37. return styles.map(style => {
  38. return `<link href="${style}" media="screen, projection" rel="stylesheet" type="text/css" charSet="UTF-8"/>`;
  39. });
  40. };
  41. const scriptMapper = scripts => {
  42. const scriptTags = [];
  43. for (let i = 0; i < scripts.length; i = i + 1) {
  44. scriptTags.push(`<script src=${scripts[i]}></script>`);
  45. }
  46. return scriptTags;
  47. };