Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
7 tasks done
Hancoson opened this issue May 18, 2018 · 0 comments
Open
7 tasks done

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

Hancoson opened this issue May 18, 2018 · 0 comments

Comments

@Hancoson
Copy link
Owner

Hancoson commented May 18, 2018

话说 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 模版的实现,相关文章>>

技术实现

  • Express
  • mongoose
  • react > 16.x
  • Nextjs
  • Node > 8.x
  • sass
  • 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 方法只会在服务端执行。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant