blog icon indicating copy to clipboard operation
blog copied to clipboard

学会这个,前端也可以和PHP程序员一样了

Open Hancoson opened this issue 6 years ago • 0 comments

话说 PHP 是世界上“最好”的语言,我不是 PHPer ,所以今天我们的主角不是 PHP ,而是前端(Nextjs)。那么问题来了,Nextjs 是什么?

Next.js is a lightweight framework for static and server-rendered applications.

说直白了:Next.js 是一个基于 React 实现的服务端渲染框架。 好了,今天我们就来聊聊 Next.js 实现。

介绍

该项目通过使用 Nextjs 技术,实现了 React 同构方案。采用 Nodejs 搭建服务,结合 Mongoose 数据库,实现了一个简单的博客系统。 也可以参考项目 v1.0 版本通过 Ejs 模版的实现,相关文章>>

技术实现

  • [x] Express
  • [x] mongoose
  • [x] react > 16.x
  • [x] Nextjs
  • [x] Node > 8.x
  • [x] sass
  • [x] isomorphic-unfetch

目录结构

├─server # 服务
│  ├─controllers # 控制器
│  ├─dto  #
│  ├─models # 模型
│  ├─routes  # 路由
│  └─service
├─pages # 页面
│  ├─…… #
│  └─index.js # 主页面
├─compontents # 组件
│  └─#……
├─config # 配置文件
│  └─#……
├─assets # 静态资源
│  └─#……
├─build # 发布目录
│  └─ #……
├─next.config.js # next配置文件
├─package.json
├─postcss.config.js # postcss配置
├─server.js # 服务入口文件
└─.babelrc

如何使用

主要针对我当前的项目>> node-blog-app 来说说使用方法:

Install

git clone https://github.com/Hancoson/node-blog-app.git

yarn

Install mongodb

brew install mongodb

Start Mongo

mongod
# or
brew services start mongodb

最后执行:

mongo

Create a datebase

use {nodeApp}

Start App

npm run dev #(start dev)

npm run build #(构建)

npm start #(启动项目)

遇到问题

项目开始的时候,也是遇到(踩)了不少的问题(坑)。接下来捡几个来说说吧。

编译

最开始 clone 了官方的 demo ,但是编译(npm run dev)的时候会遇到 (node:58300) UnhandledPromiseRejectionWarning: Error: Cannot find module 'babel-plugin-transform-runtime' 报错,后来查了资料,也在 issues 上提了,官方给我的答复是过时的 .babelrc 影响。哎~自己都浪费了半天时间,按照大神 @timneutkens 的指导,添加了新的 .babelrc ,解决了此问题。

//.babelrc
{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

获取数据

Nextjs 提供一个新的生命周期函数 getInitialProps 。具体用法如下:

import React from 'react'
export default class extends React.Component {
  static async getInitialProps({ req }) {
    //这里可以使用 isomorphic-unfetch 获取 server 端数据
    const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
    return { userAgent }
  }

  render() {
    return (
      <div>
        Hello World {this.props.userAgent}
      </div>
    )
  }
}

在页面渲染加载数据时,我们使用 getInitialProps 这个异步静态方法来获取 props (类似JSON.stringify)对象。初始化页面的时候,getInitialProps 方法只会在服务端执行。

Hancoson avatar May 18 '18 06:05 Hancoson