前言
nextjs 作为react 服务端渲染框架,支持ssr(请求时预渲染) ssg(构建时预渲染)…等渲染模式,其在seo 搜索引擎搜索优化有着不错的表现 ,支持ts。
提示:以下是本篇文章正文内容,下面案例可供参考
一、what is nextjs?
react 的服务端渲染框架,也就是node 服务器,类似框架有:nuxt.js(vue),nest.js( Angular ,有点像spring框架)。
二、安装使用
1.create-next-app
如果你想要ts开发
npx create-next-app@latest --typescript
区别:默认是js 文件,如果ts,则ts文件和多出一个tsconfig.json
这种直接npm run dev
即可
2. 手动安装
1. npm init -y
2. npm install next react react-dom
3. 在你的package.json 加上
"scripts": {
"dev": "next dev",//开发
"build": "next build",//构建
"start": "next start",//运行服务器构建
"lint": "next lint"//eslint
}
这三个是最基础的nextjs 应用。
这里只是一个空白文件下面手动一步步构建
3. pages
- 新建文件夹
pages/helloWord/index.js
function About() {
return <div>helloWord</div>;
}
export default About;
npm run dev
- 浏览器输入http://localhost:3000/helloWord
恭喜你,你的第一个nextjs 应用跑起来了。
特殊文件夹说明 pages/index.js
home 页面,也就是http://localhost:3000的页面pages/api
api 路由pages/_app.js
用于做layout 布局,如果你的页面都是包含相同的布局,可以使用这个,比如header 和footer
// pages/_app.js
import Layout from '../components/layout'
export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
4. public
放静态资源,此文件夹还可用于存放 robots.txt、favicon.ico、Google 站点验证文件以及任何其它静态文件(包括 .html 文件)!
访问
5. styles
放css 文件,需要时在_app.js 全局引用,
其他page 页只能通过命名*.module.css
,然后在js 中引用,‘sass需要配置’
import styles from "./index.module.css";
function About() {
return <div className={styles.helloWorld}>helloWord</div>;
}
export default About;
6. config
.eslintrc.json
自带eslint 规则
{
"extends": "next/core-web-vitals"
}
.gitignore
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
}
module.exports = nextConfig
tsconfig.json
、next-env.d.ts
需要把你.js 全部换成.tsx
npm i -D @types/node @types/react @types/react-dom eslint eslint-config-next typescript
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
总结
以上就是next的入门了
接下来就是用nextjs 重构一下我的网站