背景:
接上篇文章如何快速的撸出一个官网(包含git操作脚本),制作出来的网站的结构和内容都是用js生成,对seo不友好;该篇文章,会告知如何 服务端预编译页面内容,开启ssr;并提供部署脚本;
开始
代码修改
- 参考umijs 官网的介绍,开启ssr方法(https://v2.umijs.org/zh/guide/ssr.html#服务端);
- .umirc.js 修改为底下的内容(特别注意的点是,ssr内容要设置为{disableExternal: true,})
export default {ssr: {disableExternal: true,},plugins: [['umi-plugin-react', {antd: true,}],['@umijs/plugin-prerender', {include: '/',htmlSuffix: true,}],],exportStatic: {htmlSuffix: true,dynamicRoot: true,},}
- server.js 设置为底下内容
// bar.jsconst server = require('umi-server');const http = require('http');const { createReadStream } = require('fs');const { join, extname } = require('path');const root = join(__dirname, 'dist');const render = server({root,})const headerMap = {'.js': 'text/javascript','.css': 'text/css','.jpg': 'image/jpeg','.png': 'image/jpeg',}http.createServer(async (req, res) => {const ext = extname(req.url);const header = {'Content-Type': headerMap[ext] || 'text/html'}res.writeHead(200, header);if (!ext) {// url renderconst ctx = {req,res,}const { ssrHtml } = await render(ctx);res.write(ssrHtml);res.end()} else {// static file urlconst path = join(root, req.url);const stream = createReadStream(path);stream.on('error', (error) => {res.writeHead(404, 'Not Found');res.end();});stream.pipe(res);}}).listen(8080)console.log('http://localhost:8080');
- 本地调试: umi dev
- 打包: yarn build ;(为了避免线上访问到旧的内容;建议手动修改 dist/底下的js、css的版本号)
- 用 serve 来验证下打包后的文件的可用性:
npm i -g serveserve ./dist
线上服务器的配置
- 环境配置
//安装nodejscurl --silent --location https://rpm.nodesource.com/setup_10.x | bash -yum -y install nodejs//安装servenpm install -g cnpm --registry=https://registry.npm.taobao.orgcnpm install -g yarnyarn global add serve//启动serve ./dist
- 配置nginx转发,对外可以访问;
server {listen 80;server_name www.xxx.com;location / {proxy_pass http://localhost:5000;}}
