# nextjs-web **Repository Path**: topazur/nextjs-web ## Basic Information - **Project Name**: nextjs-web - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-01-13 - **Last Updated**: 2021-01-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). # 一、入门 - 自动编译和捆绑(使用webpack和babel) - 快速刷新 - 静态生成和服务器端渲染的./pages/ - 静态文件服务。./public/映射到/ ## 起步 ```bash npm init next-app nextjs-demo npm run dev # or yarn dev # 内置css npx create-next-app --example with-tailwindcss with-tailwindcss-app # or yarn create next-app --example with-tailwindcss with-tailwindcss-app ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. - `react页面`对应`page/*` - `pages/api`目录映射到`/api/*`; 此目录中的文件被视为[API 路由](https://nextjs.org/docs/api-routes/introduction),而不是React页面. 例如访问[http://localhost:3000/api/hello](http://localhost:3000/api/hello)即可编辑对应的`pages/api/hello.js` ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. - [Next.js GitHub 仓库](https://github.com/vercel/next.js/) ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/import?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. # 二、基本特征 ## 支持TS > 配置ts后将在项目的根目录中创建一个名为 `next-env.d.ts` 的文件。该文件确保TypeScript编译器选择Next.js类型。您无法删除它,但是,您可以对其进行编辑(但是您不必这样做)。 - Next.js自动支持`tsconfig.json`: "paths"和"baseUrl"选项 - alias ```js // next.config.js config.resolve.alias['@'] = path.resolve('./src'); // tsconfig.json { "baseUrl": ".", "paths": {"@/*": ["src/*"]}, } ``` - nuxt内置类型使用说明 ```ts // 1. 静态生成和服务器端渲染 import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next' export const getStaticProps: GetStaticProps = async (context) => { // ... } export const getStaticPaths: GetStaticPaths = async () => { // ... } export const getServerSideProps: GetServerSideProps = async (context) => { // ... } // 2. API路由 import type { NextApiRequest, NextApiResponse } from 'next' type Data = { name: string } export default (req: NextApiRequest, res: NextApiResponse) => { res.status(200).json({ name: 'John Doe' }) } // 3. Custom App import type { AppProps /*, AppContext */ } from 'next/app' function MyApp({ Component, pageProps }: AppProps) { return } ``` ## tailwindcss v2.0 ```bash # If you're on Next.js v10 npm install tailwindcss@latest postcss@latest autoprefixer@latest # If you're on Next.js v9 or older npm install tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 # Create your configuration files npx tailwindcss init -p > generate your tailwind.config.js and postcss.config.js files > NOTICE: 确保将包含TailwindCSS的文件导入pages/_app.js组件中 ``` tailwindcss - utility-first CSS framework autoprefixer - plugin to parse CSS and add vendor prefixes to CSS rules using values from Can I Use. > 从Next.js 9.5.4开始,您可以在应用程序中的任何位置从`node_modules`导入CSS文件。 ## 静态文件服务 - `next/image`需要Next.js 10或更高版本。& 从10.0.0版开始,Next.js具有内置的图像组件和自动图像优化功能。 - 请勿为public目录命名。名称不能更改,并且是用于提供静态资产的唯一目录 - 请确保没有与pages/目录中文件同名的静态文件 - 仅服务public于构建时目录中的资产。在运行时添加的文件将不可用。 - 此文件夹也是有用的robots.txt,favicon.ico,谷歌网站验证,以及任何其他静态文件(包括.html)! ## Fast Refresh > 默认情况下,所有9.4或更高版本的Next.js应用程序均启用“快速刷新” > 启用Next.js快速刷新后,大多数编辑应该在一秒钟内可见,而不会丢失组件状态。 - 局限性 - 对于类组件,不保留局部状态(仅函数组件和Hooks保留状态)。 - 您正在编辑的文件可能除了React组件之外还具有其他导出功能。 - 有时,文件会导出调用像的高阶组件的结果HOC(WrappedComponent)。如果返回的组件是类,则状态将被重置。 - 诸如匿名箭头之类的功能export default () =>
;会导致“快速刷新”不保留本地组件状态。对于大型代码库,您可以使用我们的name-default-component `code mod`。 - 提示 - 快速刷新默认情况下会在函数组件(和Hooks)中保留React局部状态。 - 有时,您可能需要强制重置状态并重新安装组件。例如,如果您要调整仅在安装时发生的动画,这会很方便。为此,您可以 `// @refresh reset` 在正在编辑的文件中的任何位置添加。该指令是文件本地的,并指示“快速刷新”在每次编辑时重新安装该文件中定义的组件。 - 您可以在开发过程中放置`console.log`或`debugger`;放入要编辑的组件中。 ## 环境变量 > 适用于9.4和更高版本的Next.js ```bash # .env HOSTNAME=localhost PORT=8080 # 1.1 Next.js将自动$VAR在.env*文件内部扩展变量; 如`$PORT=8080` HOST=http://$HOSTNAME:$PORT # 1.2 仅仅使用$实际值为的变量,则需要像这样对它进行转义:`\$`。becomes "pre$A" CORRECT=pre\$A DB_HOST=localhost DB_USER=myuser DB_PASS=mypassword # 2. 默认情况下,所有通过.env.local它加载的环境变量仅在Node.js环境中可用。 # 为了向浏览器显示变量,您必须在变量前面加上`NEXT_PUBLIC_`。 NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk # Next.js允许您在`.env(所有环境)`,`.env.development(开发环境)`和`.env.production(生产环境)`和`.env.test`中设置默认值 # `.env.local` 始终会覆盖默认设置。 # `.env`,`.env.development`和`.env.production`文件应包含在您的存储库中,因为它们定义了默认值。 # `.env.*.local` 应该添加到中.gitignore,因为这些文件将被忽略。.env.local是可以存储秘密的位置 # 每个测试执行都将通过忽略您的命令.env.local(用于覆盖默认设置)在不同的执行中使用相同的环境默认值 ``` ## 支持的浏览器和功能 > Next.js支持IE11和所有现代浏览器(Edge,Firefox,Chrome,Safari,Opera等),无需进行任何配置。 - Polyfills 透明地注入IE11兼容性所需的polyfill。为了减小包的大小,Next.js将只为需要它们的浏览器加载这些polyfill。 - 自定义babel config [.babelrc](https://nextjs.org/docs/advanced-features/customizing-babel-config) ## 约定式-`pages` > 适用于9.3及更高版本的Next.js > In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each page is associated with a route based on its file name. - `_app.**` 特殊性 - `api` directory 是 快捷后端api路由; 文件夹中的任何文件pages/api都将映射到/api/*API端点,而不是page。它们是仅服务器端的捆绑包,不会增加客户端捆绑包的大小。 - 具有 **动态路由(也称为url链接,pretty url 等)** 的页面 `[name].**` - `pages/blog/[slug].js`→ `/blog/:slug`(即`/blog/hello-world?a=b`)← `query: { "slug": "hello-world", "a": "b" }` - `pages/post/[...all].js`→ `/post/*`(即`/post/2020/id/title`)← `query: { "all": ["2020", "id", "title"] }` - `pages/post/[[...slug]].js`→ 将匹配`/post`,`/post/a`,`/post/a/b`,等等。 捕获所有路由和可选捕获所有路由之间的主要区别在于,使用可选时,不带参数的路由也会匹配(/post在上面的示例中)。 - 动态参数不能和已有固定路由冲突, 固定的优先级高 - 两种预渲染形式:静态生成和服务器端渲染 ## Data Fetching # 三、路由 ## 介绍 ### 约定式路由 规则见 上述 约定式-pages ### link ```tsx import Link from 'next/link'; // [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) 在示例中用于保持路径utf-8兼容。 1. 字符串形式 2. 对象形式 ``` ## 势在必行: 注入路由器 要访问React组件中的router对象,可以使用useRouter或withRouter。 **一般而言,我们建议使用useRouter。** ## 浅层路由 要启用浅层路由,请将shallow选项设置为true ```tsx const router = useRouter() useEffect(() => { // Always do navigations after the first render router.push('/?counter=10', undefined, { shallow: true }) }, []) ``` ### 注意事项 浅路由仅适用于相同页面URL更改。例如,假设我们还有一个名为的页面pages/about.js,您可以运行以下页面: ```ts router.push('/?counter=10', '/about?counter=10', { shallow: true }) ``` 由于这是一个新页面,因此即使我们要求执行浅层路由,它也会卸载当前页面,加载新页面并等待数据提取。 # 四、API路由 ```ts const { method, query, params, body, cookies} = req; const { statusCode, setHeader, end,/*后面是中间件实现的*/ status, json, send } = res; /*optional res.status(code)-设置状态码的功能。code必须是有效的HTTP状态代码 res.json(json)-发送JSON响应。json必须是有效的JSON对象 res.send(body)-发送HTTP响应。body可以是a string,anobject或aBuffer res.redirect([status,] path)-重定向到指定的路径或URL。status必须是有效的HTTP状态代码。如果未指定,则status默认为“ 307”“临时重定向”。*/ ``` API路由提供了内置的中间件,用于解析传入的请求(req)。这些中间件是: - req.cookies-包含请求发送的Cookie的对象。默认为{} - req.query-包含查询字符串的对象。默认为{} - req.body-包含由解析的正文的对象content-type,或者null如果未发送正文 ### 每个API路由都可以导出一个config对象以更改默认配置 ```js export const config = { api: { bodyParser: { sizeLimit: '1mb',// '500kb' -- 解析的正文允许的最大大小 bodyParser: false,// -- bodyParser启用正文解析 externalResolver: true,// -- externalResolver是一个显式标志,它告诉服务器此路由正在由外部解析器(如express或connect)处理。启用此选项将禁用针对未解决请求的警告。 }, }, } // ... // export default handler; ``` ### cors跨域中间件 ```js import Cors from 'cors' // Initializing the cors middleware const cors = Cors({ methods: ['GET', 'HEAD'], }) // Helper method to wait for a middleware to execute before continuing // And to throw an error when an error happens in a middleware function runMiddleware(req, res, fn) { return new Promise((resolve, reject) => { fn(req, res, (result) => { if (result instanceof Error) { return reject(result) } return resolve(result) }) }) } async function handler(req, res) { // Run the middleware await runMiddleware(req, res, cors) // Rest of the API logic res.json({ message: 'Hello Everyone!' }) } export default handler ``` ### 为了获得更好的类型安全性,不建议扩展req和res对象。 ```js // 纯函数 import { NextApiRequest, NextApiResponse } from 'next' import { setCookie } from '../../utils/cookies' const handler = (req: NextApiRequest, res: NextApiResponse) => { setCookie(res, 'Next.js', 'api-middleware!') res.end(res.getHeader('Set-Cookie')) } // 如果无法避免扩展这些对象,则必须创建自己的类型以包括额外的属性: type NextApiRequestWithFoo = NextApiRequest & { foo: (bar: string) => void } const handler = (req: NextApiRequestWithFoo, res: NextApiResponse) => { req.foo('bar') // we can now use `req.foo` without type errors res.end('ok') } ``` ### 优先级 匹配顺序: xxx.ts -> [xxx].ts -> [...xxx].ts ### 使用中间件 ```ts // https://github.com/senchalabs/connect - 查看常用中间件 const connect = require('connect'); const app = connect(); app.use(...); export default app; // 例子 app.use((req,res,next)=>{ // ... }) ``` ### Route Masking ```tsx // href是规范 as是实际路由 {props.title} ``` ## 动态路由 类似于pages的约定式 # API参考 ```js import { useRouter } from 'next/router' import Link from 'next/link' import Image from 'next/image' import Head from 'next/head'// 追加head信息 import { useAmp } from 'next/amp'// 该页面用于useAmp区分模式 // true -该页面仅适用于AMP // 'hybrid' -该页面将具有两个版本,一个带有AMP,另一个带有HTML export const config = { amp: 'hybrid' } ``` # Data Fetching # 高级配置 ## 支持 src Directory [src](https://nextjs.org/docs/advanced-features/src-directory) - 页面也可以src/pages作为根pages目录的替代添加。该src目录在许多应用程序中非常常见,默认情况下,Next.js支持该目录。 - src/pages如果`pages根目录(优先级高)`中存在,将被忽略 - 像next.config.js和这样的配置文件tsconfig.json应该位于根目录中,将其移至src无法使用。这同样适用于public目录 # next.config.js # 他人博客 http://www.liuweibo.cn/ https://segmentfault.com/a/1190000002804472?utm_source=sf-related [腾讯云翻译](https://cloud.tencent.com/developer/news/718886) [hexo](https://www.dazhuanlan.com/2020/03/23/5e786ff66dc44/) https://www.yevpt.com/ 好看的博客 http://maxogden.github.io/slides/nodepdx/index.html 3D博客(类似我的世界) https://onlyorca.com/ 设计创意 Marp,也就是PPT插件 Markdown代码画图: https://szp15.com/2020/03/21/diagrams-test/ wowjs