1 Star 1 Fork 0

pardon110 / next-tailwind

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
EPL-1.0

next-tailwind

react 项目,nextjs 采用 page router 及 第三代 css 框架 Tailwind

nextjs

Pages and Layouts

  • pages/_app.js
  • _app 容器组件 { Component, pageProps }
import Layout from '../components/layout';
 
export default function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

Dynamic Routes

  • 动态路由默认使用方括号包裹,Dynamic Segments can be access from useRouter.
  • [folderName]
  • [...folderName] Catch-all Segments
  • [[...folderName]] 可选
  • 应用范围: 目录和文件名都适用
Route Example URL params
pages/posts/[slug].js /posts/a { slug: 'a' }
pages/optional/[...slug].js /optional/a/b/c { slug: ['a', 'b', 'c'] }
pages/optional/[[...slug]].js /optional {}
pages/optional/[[...slug]].js /optional/a/b/c { slug: ['a', 'b', 'c'] }

project structure

  • Route Groups
(folder) Group routes without affecting routing
_folder Opt folder and all child segments out of routing
  • Parallel and Intercepted Routes
@folder Named slot
(.)folder Intercept same level
(..)folder Intercept one level above
(..)(..)folder Intercept two levels above
(...)folder Intercept from root

head 组件渲染流程

下面是 Next.js 在处理 Head 组件时的流程:

  1. 在服务端渲染阶段,Next.js 会在渲染每个页面时初始化一个全局的 HeadManager 对象。
  2. 在页面组件中,当使用 Head 组件时,会将其包含的元素添加到 HeadManager 对象中。
  3. 在服务端渲染完成后,Next.js 会将渲染完成的 HTML 携带着 HeadManager 对象发送给客户端。
  4. 当客户端加载新页面并纯客户端渲染时,Next.js 会重新初始化一个新的 HeadManager 对象。
  5. 新页面的 HTML 中包含一个特殊标记,指示 Next.js 将 HeadManager 对象中的元素更新到 <head> 中。
  6. 当客户端浏览器解析 HTML 时,它会在发现特殊标记时,触发 HeadManager 对象的 updateHead 方法,使其将 Head 组件中的新元素添加到页面的 <head> 部分中。
  7. 每当需要更新页面的 <head> 部分中的元素时(例如切换到新页面),HeadManager 对象的 updateHead 方法都会被触发,以实时更新视图。
    +-------------+                       +----------------------+
    |  Next.js     |                       |  Browser             |
    |  Server      |                       |                      |
    +------+------|                       |                      |
           |      |                       |                      |
           |      |                       |                      |
           |      |                       |                      |
           |      |                1. Generate HTML with          |
           |      |<---------------------------------------------+
           |      |   HeadManager object on each page
           |      |
           |      |
           |      |
           |      |   2. Send HTML with HeadManager object
           |      |      to client
           |      +---------------------------------------------->+
           |      |
           |      |
           |      |                  4. Initialize new HeadManager
           |      |<----------------------------------------------+
           |      |                     object on client
   3. Render |      |
   component|      |                  5. Update <head> using new
   with     |      |<----------------      HeadManager object
   Head    |      |
   component|      |                  6. Perform client-side routing
           |      |<----------------      to new page
           |      | 
           |      |   7. Repeat steps 3-6 for each page change
           |      |
  • 在 Next.js 中,Head 组件可以出现在任意非 head 标签之内,只需确保它位于组件返回的 JSX 根元素的直接内部即可

Environment Variable Load Order

  1. process.env
  2. .env.$(NODE_ENV).local
  3. .env.local (Not checked when NODE_ENV is test.)
  4. .env.$(NODE_ENV)
  5. .env

hooks/properties for nextjs

  • Next.js 中,每个页面都是一个 React 组件,可以通过导出默认属性来定义页面的行为和内容
  • getServerSideProps:用于在每次请求时获取页面的数据,返回一个对象,包含页面的 props。这个方法在每次请求时都会被调用,可以用于动态生成页面内容。
  • getInitialProps:用于在每次请求时获取页面的数据,返回一个对象,包含页面的 props。这个方法已经被废弃,推荐使用 getServerSidePropsgetStaticProps
  • pageProps:包含页面的 props,可以在组件中直接使用。
  • Component:页面的 React 组件,可以在组件中直接使用。
  • getStaticPaths (Static Generation): 为动态路由参数构建所需的路径
  • getStaticProps:(Static Generation): 负责根据指定的动态路由参数获取数据

Shallow Routing

  • 它只匹配 URL 的第一层路径,而不考虑其后续路径。
  • 意味着在 Shallow Routing 中,所有具有相同路径的 URL 都将被映射到同一个页面或组件上。
  • 应用场景 路由策略通常用于简单的页面或组件,例如主页、登录页等
    router.push('/?counter=10', '/about?counter=10', { shallow: true })

API Routes

  • Every API Route can export a config object to change the default configuration
    export const config = {
      api: {
        bodyParser: {
          sizeLimit: '1mb',
        },
      },
    };

Authenticating

  • pattern
    • data-fetching strategy
    • static generation
    • server-side
  • 身份验证模块
    • with-iron-session
    • next-auth-example
    • with-passport
    • with-passport-and-next-connect
    • auth0

middleware.js

  • matching paths order

    • headers from next.config.js
    • redirects from next.config.js
    • Middleware (rewrites, redirects, etc.)
    • beforeFiles (rewrites) from next.config.js
    • Filesystem routes (public/, _next/static/, pages/, app/, etc.)
    • afterFiles (rewrites) from next.config.js
    • Dynamic Routes (/blog/[slug])
    • fallback (rewrites) from next.config.
  • server code

    // middleware.js
    export default function myServerMiddleware(req, res, next) {
      console.log('This is my server middleware');
      next();
    }
    // pages/api/mypage.js
    import myServerMiddleware from '../../middleware';
    
    // 页面组件或 API 路由处理函数
    function handler(req, res) {
      return res.status(200).json({ text: 'Hello' });
    }
    
    // 使用服务端中间件
    export default myServerMiddleware(handler);
  • client code

    // middleware.js
    function myClientMiddleware(request, response, next) {
      console.log('This is my client middleware');
      // 在请求头中添加自定义信息
      request.headers["x-my-header"] = "hello";
      next();
    }
    
    export default myClientMiddleware;
    • useEffect
    // pages/index.js
    import myClientMiddleware from '../middleware';
    
    function IndexPage() {
      useEffect(() => {
        myClientMiddleware();
      }, []); // 在组件加载时执行中间件函数
    
      return <div>Hello world</div>;
    }
    
    export default IndexPage;
  • 路由配置

    // pages/middleware.js
    const legacyPrefixes = ['/docs', '/blog'];
     
    export default async function middleware(req) {
      const { pathname } = req.nextUrl;
     
      if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
        return NextResponse.next();
      }
     
      // apply trailing slash handling
      if (
        !pathname.endsWith('/') &&
        !pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
      ) {
        req.nextUrl.pathname += '/';
        return NextResponse.redirect(req.nextUrl);
      }
    }
  • 通过配置实现

// next.config.js

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:3000/api/:path*',
      },
    ]
  },

  async redirects() {
    return [
      {
        source: '/old-path',
        destination: '/new-path',
        permanent: true,
      },
    ]
  },
}

rendering

  • 同构应用

    同构模块的出现是为了解决单页应用(SPA)在网络环境差、首次加载时间长、SEO 不友好等方面的问题。

    在单页应用中,大部分 HTML、CSS、JS 等资源只在首次加载时请求一次,以后的操作只会请求 JSON 数据,通过 AJAX 异步刷新页面。这种应用方式的好处在于用户操作更顺畅,但缺 点也很明显:首次加载速度慢、SEO 不友好。

    单页应用首次加载慢的原因是因为在请求 HTML 文件之外,还需要加载大量的 JavaScript 文件来构建页面,这些文件在首次加载时会花费很长时间。而且搜索引擎的爬虫只会对页面进行解析并拿取其中的文本信息,对于单页应用中使用 ajax 获取内容生成的数据会不良影响 SEO。

    为了解决以上问题,同构模块就出现了。同构应用是指在服务端运行一段 JS 代码,生成 HTML 文件后再返回给客户端。也就是说,同样一段代码,在服务器端和客户端都会执行,处理逻辑相同,生成的结果也完全一致。因此同构应用能够在第一次请求时快速返回完整的 HTML 页面,提高页面加载速度,而且因为服务端构建页面返回给客户端所得到的 HTML 已经包含所有的内容,包括从服务端读取的数据,因此对搜索引擎的爬取也是十分友好的。

nextjs 前后端同构模块, build --> hydration 两个主阶段渲染

前后端同构基本原理

将一部分代码在服务器端运行,将另一部分代码在浏览器端运行 并将它们的状态和数据同步. ReactDOM.hydrate()方法将服务器端生成的HTML(含注入的服务端数据__NEXT_DATA__)在客户端

  • ReactDomServer.renderToString(): 服务端渲染
  • React.hydrate() 客户端渲染 水化?
  • ReactDOM.render() 基本渲染
  • ReactDom.createPortal() 脱离父组件渲染,如弹窗...

tree

  • 虚拟 DOM
  • Fiber 支持可中断渲染 16+
  • browser 相关树 Dom 树, css rule 规则树, render 渲染树

React Hook

  • useCallback 将函数的引用进行缓存,避免在每次组件重新渲染时都要重新创建函数
  • useRef 在函数式组件中引用 DOM 元素或任何值。它类似于使用 ref 属性的类组件
  • useState 在函数式组件中添加状态。它返回一个包含状态值和一个更新状态的函数的数组。
  • useReducer 接受一个 reducer 函数和初始状态,返回一个包含当前复杂状态和 dispatch 函数的数组
  • useEffect 在函数式组件中定义副作用
  • useContext 在函数式组件中使用 React 上下文
  • useMemo 在函数式组件中缓存计算结果,只有当依赖项更改时才会重新计算

About app router

  • A page is UI that's unique to a route

    // app/feed/[item]/page.js
    
    export default function Page({ params, searchParams }) {
      return <h1>My Page</h1>;
    }
  • params (optional)

    路径格式 请求路径 参数对象
    app/shop/[slug]/page.js /shop/1 { slug: '1' }
    app/shop/[category]/[item]/page.js /shop/1/2 { category: '1', item: '2' }
    app/shop/[...slug]/page.js /shop/1/2 { slug: ['1', '2'] }
  • searchParams (optional)

    URL searchParams
    /shop?a=1 { a: '1' }
    /shop?a=1&b=2 { a: '1', b: '2' }
    /shop?a=1&a=2 { a: ['1', '2'] }

    React

Route Handlers vs Api routes

  • They do not participate in layouts or client-side navigations like page.
  • There cannot be a route.js file at the same route as page.js.
  • Each route.js or page.js file takes over all HTTP verbs for that route.
Page Route Result
app/page.js app/route.js Conflict
app/page.js app/api/route.js Valid
app/[user]/page.js app/api/route.js Valid
  • vs
    • Route Handlers
      • 通过匹配 Pages 目录下的文件名(文件名即路由)来映射到不同的页面
      • 通过导出一个 React 组件来描述页面内容和行为
    • API routes
      • 通过定义 Pages/api 目录下的特殊文件来创建
      • 接收和处理不同的 HTTP 请求,并返回 JSON 格式的数
      • 不需要渲染组件,而只需要处理数据
Eclipse Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. "Contributor" means any person or entity that distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 3. REQUIREMENTS A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: a) it complies with the terms and conditions of this Agreement; and b) its license agreement: i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. When the Program is made available in source code form: a) it must be made available under this Agreement; and b) a copy of this Agreement must be included with each copy of the Program. Contributors may not remove or alter any copyright notices contained within the Program. Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.

简介

技术验证,笔记同步 nextjs + Tailwind 展开 收起
NodeJS 等 4 种语言
EPL-1.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
NodeJS
1
https://gitee.com/pardon110/next-tailwind.git
git@gitee.com:pardon110/next-tailwind.git
pardon110
next-tailwind
next-tailwind
master

搜索帮助