登录
首页 >  文章 >  前端

掌握 Nextjs:4 年内构建大型项目的终极指南

来源:dev.to

时间:2024-08-05 14:45:54 312浏览 收藏

从现在开始,努力学习吧!本文《掌握 Nextjs:4 年内构建大型项目的终极指南》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

掌握 Nextjs:4 年内构建大型项目的终极指南

简介:驯服 next.js 丛林

嘿,代码管理员和 next.js 爱好者! ? 您是否感觉像印第安纳琼斯一样,在组件、钩子和配置文件的茂密丛林中进行黑客攻击?别担心,在这次冒险中你并不孤单。我曾经在那里,手里拿着砍刀,试图在大型 next.js 项目的荒野中开辟出一条道路。

但事情是这样的:有了正确的地图和工具,您的 next.js 丛林可以成为一个组织良好、欣欣向荣的生态系统。在这份综合指南中,我将分享我在构建大型 next.js 项目方面来之不易的智慧。无论您是扩展现有应用程序还是从头开始创建新的庞然大物,本指南都是您值得信赖的指南针。

为什么 next.js 项目结构可以成就你,也可以毁掉你

在深入讨论细节之前,让我们先谈谈为什么花时间在项目结构上就像投资一双好的编码鞋一样 – 它会带你走得更远,让你感到舒适:

  1. 开发者理智:良好的结构意味着更少的时间玩“威利在哪里?”使用您的组件和更多时间进行实际编码。
  2. 团队和谐:当您的团队可以蒙着眼睛导航项目时,协作变得轻而易举,而不是一场战斗。
  3. 可扩展性:一个结构良好的项目会像快乐的植物一样有机地生长,而不是突变成代码怪物。
  4. 性能提升:当您的项目按逻辑组织时,next.js 优化功能效果最佳。
  5. 可维护性:未来的你(或者继承你的项目的可怜的灵魂)将永远感激一个干净、直观的结构。

让您想要构建它的 next.js 项目结构

好吧,请打鼓! ? 这是一个在大规模 next.js 开发的战壕中经过考验的结构:

? my-awesome-nextjs-project
|
|_ ? app
|  |_ ? (auth)
|  |  |_ ? login
|  |  |  |_ ? page.tsx
|  |  |  |_ ? layout.tsx
|  |  |_ ? register
|  |     |_ ? page.tsx
|  |     |_ ? layout.tsx
|  |_ ? dashboard
|  |  |_ ? page.tsx
|  |  |_ ? layout.tsx
|  |_ ? api
|  |  |_ ? users
|  |  |  |_ ? route.ts
|  |  |_ ? posts
|  |     |_ ? route.ts
|  |_ ? layout.tsx
|  |_ ? page.tsx
|
|_ ? components
|  |_ ? ui
|  |  |_ ? button.tsx
|  |  |_ ? card.tsx
|  |  |_ ? modal.tsx
|  |_ ? forms
|  |  |_ ? loginform.tsx
|  |  |_ ? registerform.tsx
|  |_ ? layouts
|     |_ ? header.tsx
|     |_ ? footer.tsx
|     |_ ? sidebar.tsx
|
|_ ? lib
|  |_ ? api.ts
|  |_ ? utils.ts
|  |_ ? constants.ts
|
|_ ? hooks
|  |_ ? useuser.ts
|  |_ ? useauth.ts
|  |_ ? useposts.ts
|
|_ ? types
|  |_ ? user.ts
|  |_ ? post.ts
|  |_ ? api.ts
|
|_ ? styles
|  |_ ? globals.css
|  |_ ? variables.css
|
|_ ? public
|  |_ ? images
|  |  |_ ? logo.svg
|  |  |_ ? hero-image.png
|  |_ ? fonts
|     |_ ? custom-font.woff2
|
|_ ? config
|  |_ ? seo.ts
|  |_ ? navigation.ts
|
|_ ? next.config.js
|_ ? package.json
|_ ? tsconfig.json
|_ ? .env.local
|_ ? .gitignore

现在,让我们分解一下,看看为什么每部分对于您的 next.js 杰作都至关重要。

next.js 应用程序的核心:应用程序目录

应用程序目录是神奇发生的地方。它是 next.js 13+ 项目的核心,利用新的 app router:

? app
|_ ? (auth)
|  |_ ? login
|  |_ ? register
|_ ? dashboard
|_ ? api
|_ ? layout.tsx
|_ ? page.tsx

路由分组为 (auth)

(auth) 文件夹是一种巧妙的方法,可以在不影响 url 结构的情况下对相关路由进行分组。它非常适合组织与身份验证相关的页面。

// app/(auth)/login/page.tsx
export default function loginpage() {
  return <h1>welcome to the login page</h1>;
}

api 路由:伪装的后端

保持 api 目录中后端逻辑的整洁。每个文件都成为一个 api 路由:

// app/api/users/route.ts
import { nextresponse } from 'next/server';

export async function get() {
  // fetch users logic
  return nextresponse.json({ users: ['alice', 'bob'] });
}

布局和页面:ui 的构建块

使用layout.tsx创建跨页面一致的设计:

// app/layout.tsx
export default function rootlayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

每个 page.tsx 代表您的应用程序中的唯一路线:

// app/page.tsx
export default function homepage() {
  return <h1>welcome to our awesome next.js app!</h1>;
}

组件:您的 next.js 乐高套装

将组件视为乐高积木。组织得很好,它们很容易找到并且使用起来很有趣:

? components
|_ ? ui
|_ ? forms
|_ ? layouts

ui 组件:构建块

创建可重用的 ui 元素,以保持整个应用程序的一致性:

// components/ui/button.tsx
export default function button({ children, onclick }) {
  return (
    <button onclick={onclick} classname="bg-blue-500 text-white py-2 px-4 rounded">
      {children}
    </button>
  );
}

表单组件:让数据输入变得轻而易举

封装表单逻辑以获得更干净、更易于维护的代码:

// components/forms/loginform.tsx
import { usestate } from 'react';
import button from '../ui/button';

export default function loginform({ onsubmit }) {
  const [email, setemail] = usestate('');
  const [password, setpassword] = usestate('');

  return (
    <form onsubmit={(e) => {
      e.preventdefault();
      onsubmit(email, password);
    }}>
      <input type="email" value={email} onchange={(e) => setemail(e.target.value)} />
      <input type="password" value={password} onchange={(e) => setpassword(e.target.value)} />
      <button type="submit">log in</button>
    </form>
  );
}

布局组件:ui 的框架

使用可重用的布局组件创建一致的页面结构:

// components/layouts/header.tsx
import link from 'next/link';

export default function header() {
  return (
    <header>
      <nav>
        <link href="/">home</link>
        <link href="/dashboard">dashboard</link>
        <link href="/profile">profile</link>
      </nav>
    </header>
  );
}

支持演员:lib、hooks 和类型

这些目录是您项目的无名英雄:

lib:你的实用腰带

在此处存储辅助函数和常量:

// lib/utils.ts
export function formatdate(date: date): string {
  return date.tolocaledatestring('en-us', { year: 'numeric', month: 'long', day: 'numeric' });
}

// lib/constants.ts
export const api_base_url = process.env.next_public_api_url || 'https://api.example.com';

hooks:自定义 react superpower

创建自定义钩子来封装复杂的逻辑:

// hooks/useuser.ts
import { usestate, useeffect } from 'react';
import { fetchuser } from '../lib/api';

export function useuser(userid: string) {
  const [user, setuser] = usestate(null);
  const [loading, setloading] = usestate(true);

  useeffect(() => {
    fetchuser(userid).then(userdata => {
      setuser(userdata);
      setloading(false);
    });
  }, [userid]);

  return { user, loading };
}

类型:typescript 最好的朋友

定义您的 typescript 接口和类型:

// types/user.ts
export interface user {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

// types/post.ts
export interface post {
  id: string;
  title: string;
  content: string;
  authorid: string;
  createdat: date;
}

设计您的 next.js 杰作

将您的样式整理在样式目录中:

/* styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* your custom global styles here */
body {
  font-family: 'arial', sans-serif;
}

/* styles/variables.css */
:root {
  --primary-color: #3490dc;
  --secondary-color: #ffed4a;
  --text-color: #333333;
}

公共资产:应用程序的面貌

公共目录是静态资产的所在地。优化图像并使用自定义字体让您的应用程序大放异彩:

import image from 'next/image';

export default function logo() {
  return <image src="/images/logo.svg" alt="company logo" width={200} height={50} />;
}

配置:项目的支柱

不要忘记根目录中的这些重要文件:

// next.config.js
module.exports = {
  images: {
    domains: ['example.com'],
  },
  // other next.js config options
};

// .env.local
database_url=postgresql://username:password@localhost:5432/mydb
next_public_api_url=https://api.example.com

大规模 next.js 成功的专业技巧

  1. 拥抱 app router:它不仅是新的,而且是新的。它是性能和嵌套布局的游戏规则改变者。
  2. 代码分割是你的朋友:使用动态导入来保持你的应用程序敏捷:
   import dynamic from 'next/dynamic';

   const dynamiccomponent = dynamic(() => import('../components/heavycomponent'));
  1. 优化这些图像:next.js 的图像组件就像图像的私人教练:
   import image from 'next/image';

   export default function hero() {
     return <image src="/hero-image.png" alt="hero" width={1200} height={600} priority />;
   }
  1. 服务器组件 ftw:使用它们来削减你的客户端 javascript:
   // this component will be rendered on the server by default in next.js 13+
   export default async function userprofile({ userid }) {
     const user = await fetchuser(userid);
     return <div>welcome, {user.name}!</div>;
   }
  1. 获胜的 api 路由:保持服务器端逻辑的安全和分离:
   // pages/api/posts.ts
   import type { NextApiRequest, NextApiResponse } from 'next';

   export default async function handler(req: NextApiRequest, res: NextApiResponse) {
     if (req.method === 'GET') {
       const posts = await fetchPosts();
       res.status(200).json(posts);
     } else {
       res.status(405).end(); // Method Not Allowed
     }
   }

总结:您的 next.js 项目井井有条并准备好扩展

现在你已经有了它——一个让你的大型 next.js 项目感觉就像一台运转良好的机器的结构。请记住,这不是一个一刀切的解决方案。请随意调整它以满足您项目的独特需求。

通过遵循这种结构,您将花更少的时间去思考事情的发展方向,而花更多的时间来构建出色的功能。你的代码会更干净,你的团队会更快乐,你的项目会像梦想一样扩展。

所以,你还在等什么?在您的下一个项目中尝试一下这个结构。未来的你(和你的队友)会为此向你击掌!

祝您编码愉快,祝您的 next.js 项目始终井井有条且没有错误! ?


请记住,成功的大型 next.js 项目的关键不仅仅在于初始设置,还在于随着项目的发展如何维护和发展您的结构。保持灵活性,不断学习,并且在需要时不要害怕重构。你已经得到了这个!

本篇关于《掌握 Nextjs:4 年内构建大型项目的终极指南》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>