快速入门:连openai都在用的Remix前端框架如何

快速开始

本指南将帮助您快速上手 Remix,从零开始创建一个基础项目,掌握其关键概念和基本操作。


🚀 安装和初始化项目

📁 创建名为 my-remix-app 的脚手架项目并且运行

  1. 创建新项目

    在命令行中运行以下命令来创建名为 my-remix-app 的项目:

    bash 复制代码
    npx create-remix@latest my-remix-app
  2. 选择安装选项

    在安装过程中,您需要选择:

    • 目标环境:Remix App Server(或选择 Express,Vercel,Netlify 等部署平台)
    • 类型:TypeScript(推荐)
    • 包管理器:npm, yarn 或 pnpm(推荐使用 pnpm 以获得更快的性能)
  3. 运行项目

    进入项目目录并启动开发服务器:

    bash 复制代码
    cd my-remix-app
    npm run dev
  4. 访问项目

    在浏览器中打开 http://localhost:3000 以查看您的 Remix 应用程序。


📄 创建一个页面和一个新 API 路由

  1. 创建页面

    在 app/routes/ 目录下,创建一个新的页面文件,例如 about.tsx:

    tsx 复制代码
    // app/routes/about.tsx
    export default function AboutPage() {
      return (
        <div>
          <h1>关于我们</h1>
          <p>欢迎来到"关于我们"页面,这是一个演示的静态页面。</p>
        </div>
      );
    }

    访问 http://localhost:3000/about 即可看到新的页面。

  2. 创建 API 路由

    在 app/routes/api/ 目录中,创建一个名为 data.ts 的新文件:

    tsx 复制代码
    // app/routes/api/data.ts
    export function loader() {
      return new Response(JSON.stringify({ message: "Hello from the API!" }), {
        headers: { "Content-Type": "application/json" },
      });
    }

    访问 http://localhost:3000/api/data 即可查看返回的 JSON 数据:

    json 复制代码
    {
      "message": "Hello from the API!"
    }

🔄 创建获取加载远程数据和缓存机制

  1. 加载远程数据

    使用 Remix 的 loader 函数来加载远程数据:

    tsx 复制代码
    // app/routes/posts.tsx
    import { json } from "@remix-run/node";
    import { useLoaderData } from "@remix-run/react";
    
    export async function loader() {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts');
      const posts = await response.json();
      return json(posts);
    }
    
    export default function PostsPage() {
      const posts = useLoaderData();
    
      return (
        <div>
          <h1>博客文章</h1>
          <ul>
            {posts.map(post => (
              <li key={post.id}>
                <h2>{post.title}</h2>
                <p>{post.body}</p>
              </li>
            ))}
          </ul>
        </div>
      );
    }

    访问 http://localhost:3000/posts 即可看到从远程接口加载的博客文章列表。

  2. 缓存机制(可选)

    为了避免多次重复请求,您可以在 loader 中实现简单的内存缓存:

    tsx 复制代码
    // app/routes/posts.tsx
    let cache = null;
    
    export async function loader() {
      if (!cache) {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
        cache = await response.json();
      }
      return new Response(JSON.stringify(cache), {
        headers: { "Content-Type": "application/json" },
      });
    }

    这样,第一次请求将加载数据并将其存储在内存中,后续的请求将使用缓存中的数据。
    注意:这是一个简单的内存缓存示例,通常生产环境中使用 Redis、Memcached 或其他持久性缓存解决方案。


🗄️ 存储数据到本地文件 log.txt

  1. 安装 fs-extra 模块

    bash 复制代码
    npm install fs-extra
  2. 编写写入日志的逻辑

    在 app/utils/logger.ts 中创建一个简单的日志记录函数:

    tsx 复制代码
    import fs from 'fs-extra';
    
    export async function writeLog(message: string) {
      const logPath = './log.txt';
      const timestamp = new Date().toISOString();
      const logMessage = `[${timestamp}] ${message}\n`;
      await fs.appendFile(logPath, logMessage);
    }
  3. 使用日志功能

    在 app/routes/api/data.ts 中使用日志函数:

    tsx 复制代码
    import { writeLog } from '~/utils/logger';
    
    export async function loader() {
      await writeLog('API /api/data 被调用');
      return new Response(JSON.stringify({ message: "Hello from the API!" }), {
        headers: { "Content-Type": "application/json" },
      });
    }

🔗 从 index 页面跳转到 about 页面

  1. 修改 app/routes/index.tsx 文件

    tsx 复制代码
    import { Link } from "@remix-run/react";
    
    export default function IndexPage() {
      return (
        <div>
          <h1>欢迎来到 Remix 应用程序</h1>
          <Link to="/about">关于我们</Link>
        </div>
      );
    }
  2. 查看效果

    在浏览器中访问 http://localhost:3000,单击"关于我们"链接,将跳转到 /about 页面。

相关推荐
程序员Sunday20 分钟前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
Setsuna_F_Seiei38 分钟前
前端转型 Agent 开发 06 之 Agent Memory 记忆系统(让 Agent 更智能,更懂你)
前端·agent·ai编程
YangYang9YangYan1 小时前
2027 秋招|数据科学与大数据技术面试项目价值回答思路,告别纯代码描述
大数据·面试·职场和发展
zhangzeyuaaa1 小时前
Ruby 多线程、GVL(GIL)与 Mutex 完全指南
开发语言·前端·ruby
默_笙2 小时前
🌊 向量库和 ES 都查不出"关系",我只好给奶茶建了一张人脉网
前端·javascript
邓江洲2 小时前
一道经典的 NSString 内存面试题
面试
优选资讯2 小时前
标签打印软件怎么对接 Excel 数据
前端·excel
一个风轻云淡3 小时前
GCC 和 GDB命令简单解读
java·linux·前端
u0111026754 小时前
图片处理接口如何统一错误信息 前端提示与后端错误码设计
前端·状态模式
福兮说4 小时前
浏览器里把 iPhone 的 HEIC 转成 JPG:Chrome 解不开、转完大了七成、拍摄时间全丢,六个坑实测
前端·javascript·图像处理·chrome·ios·iphone·heic