背景:

接上篇文章如何快速的撸出一个官网(包含git操作脚本),制作出来的网站的结构和内容都是用js生成,对seo不友好;该篇文章,会告知如何 服务端预编译页面内容,开启ssr;并提供部署脚本;

开始

代码修改

  1. export default {
  2. ssr: {
  3. disableExternal: true,
  4. },
  5. plugins: [
  6. [
  7. 'umi-plugin-react', {
  8. antd: true,
  9. }
  10. ],
  11. ['@umijs/plugin-prerender', {
  12. include: '/',
  13. htmlSuffix: true,
  14. }],
  15. ],
  16. exportStatic: {
  17. htmlSuffix: true,
  18. dynamicRoot: true,
  19. },
  20. }
  • server.js 设置为底下内容
  1. // bar.js
  2. const server = require('umi-server');
  3. const http = require('http');
  4. const { createReadStream } = require('fs');
  5. const { join, extname } = require('path');
  6. const root = join(__dirname, 'dist');
  7. const render = server({
  8. root,
  9. })
  10. const headerMap = {
  11. '.js': 'text/javascript',
  12. '.css': 'text/css',
  13. '.jpg': 'image/jpeg',
  14. '.png': 'image/jpeg',
  15. }
  16. http.createServer(async (req, res) => {
  17. const ext = extname(req.url);
  18. const header = {
  19. 'Content-Type': headerMap[ext] || 'text/html'
  20. }
  21. res.writeHead(200, header);
  22. if (!ext) {
  23. // url render
  24. const ctx = {
  25. req,
  26. res,
  27. }
  28. const { ssrHtml } = await render(ctx);
  29. res.write(ssrHtml);
  30. res.end()
  31. } else {
  32. // static file url
  33. const path = join(root, req.url);
  34. const stream = createReadStream(path);
  35. stream.on('error', (error) => {
  36. res.writeHead(404, 'Not Found');
  37. res.end();
  38. });
  39. stream.pipe(res);
  40. }
  41. }).listen(8080)
  42. console.log('http://localhost:8080');
  • 本地调试: umi dev
  • 打包: yarn build ;(为了避免线上访问到旧的内容;建议手动修改 dist/底下的js、css的版本号)
  • 用 serve 来验证下打包后的文件的可用性:
  1. npm i -g serve
  2. serve ./dist

线上服务器的配置

  • 环境配置
  1. //安装nodejs
  2. curl --silent --location https://rpm.nodesource.com/setup_10.x | bash -
  3. yum -y install nodejs
  4. //安装serve
  5. npm install -g cnpm --registry=https://registry.npm.taobao.org
  6. cnpm install -g yarn
  7. yarn global add serve
  8. //启动
  9. serve ./dist
  • 配置nginx转发,对外可以访问;
  1. server {
  2. listen 80;
  3. server_name www.xxx.com;
  4. location / {
  5. proxy_pass http://localhost:5000;
  6. }
  7. }