文章目录
1、手动搭建
1、新建项目文件夹
npm init 选着默认设置
npm i react react-dom next
在根目录新建文件夹 pages,nextJs 所有的文件都放在这里,他会根据页面的路径生成路由
2、修改启动项
修改package.json 文件 scripts 启动项
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "dev": "next",
+ "build": "next build",
+ "start": "next start"
}
npm run dev 启动项目
因为pages 文件夹是空的 所以访问 localhost:3000 会 404
在 next.js 的页面中 是不需要引入 react next 已经全局引入。实现的机制是使用了React.createElement(component)
2、脚手架搭建
1、全局安装脚手架
npm i -g create-next-app
2、创建项目
create-next-app clinextjs
or
create next-app clinextjs
创建项目有多种方式 本位以手动创建的项目为模板继续进行
3、next.js 作为Koa中间件使用
- next.js自身带有服务器,但是只处理ssr渲染
- 处理HTTP请求并处理请求数据返回相应的内容
- nextjs 提供的服务器服务,开发时侵入不了,处理不了一些服务端处理的业务逻辑,因此我们通过koa搭建node 服务
在指定根目录创建 server文件夹 存放node koa 代码1、安装Koa
npm i koa --save-dev
2、启动koa配置服务
server/server.js
// 引入Koa && next
const Koa = require('koa');
const next = require('next');
// 判断环境
const dev = process.env.NODE_ENV === 'production';
// 环境传给next
const app = next({ dev }) ;
// 获取请求
const handle = app.getRequestHandler();
// app.prepare().then(() => {
// const server = new Koa();
// server.use(async (ctx, next) => {
// await handle(ctx.req, ctx.res)
// ctx.respond = false;
// })
// server.listen(3000, () => {
// console.log('http://localhost:3000');
// })
// })
// 实例化出来一个服务
const server = new Koa();
// koa 中间件
server.use(async (ctx, next) => {
ctx.body = `<h1>Koa server</h1>${ctx.path}`
await next();
})
// 监听 3000 端口
server.listen(3000, () => {
console.log('http://localhost:3000');
})
修改启动项
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
- "dev": "next",
+ "dev": "node server/server.js",
"build": "next build",
"start": "next start"
},
启动项目时要先 build 一下
3、安装 “koa-router”
npm i koa-router --save-dev
server/server.js
const Koa = require('koa');
const next = require('next');
const Router = require('koa-router');
// 判断环境
const dev = process.env.NODE_ENV === 'production';
const app = next({ dev }) ;
const handle = app.getRequestHandler();
const server = new Koa();
// 实例化 router
const router = new Router();
// 匹配不同的路由进行返回
router.get('/json', (ctx) => {
ctx.body = {success: true}
ctx.set('Content-Type', 'application/json')
})
router.get('/test', (ctx) => {
ctx.body = '<h1>koa-router</h1>'
})
server.use(router.routes())
server.listen(3000, () => {
console.log('http://localhost:3000');
})