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

快速开始

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


🚀 安装和初始化项目

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

  1. 创建新项目

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

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

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

    • 目标环境:Remix App Server(或选择 ExpressVercelNetlify 等部署平台)
    • 类型:TypeScript(推荐)
    • 包管理器:npm, yarnpnpm(推荐使用 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 页面。

相关推荐
一条小鲨鱼15 分钟前
所遇到的响应式问题
前端·vue.js
Ruihong17 分钟前
你的 Vue v-for,VuReact 会编译成什么样的 React 代码?
vue.js·react.js·面试
M ? A17 分钟前
你的 Vue 路由,VuReact 会编译成什么样的 React 路由?
前端·javascript·vue.js·经验分享·react.js·面试·vureact
L.Cheng19 分钟前
谷歌浏览器如何禁用自动更新_Chrome关闭后台升级程序
前端·chrome
donecoding25 分钟前
类型与语法的“直觉对齐”:TS 切入的 Go 语言初体验
前端·typescript·go
web守墓人26 分钟前
【linux】Mubuntu v1.0.7发布:支持codex cli完整运行
前端·codex
WYiQIU26 分钟前
宇树科技Web前端岗(AI方向),这不算泄题吧......
前端·vue.js·人工智能·笔记·科技·面试·职场和发展
Januea26 分钟前
Chrome的Fetch/XHR是什么?
前端·chrome
CoderJia程序员甲28 分钟前
GitHub 热榜项目 - 日榜(2026-04-17)
ai·大模型·llm·github·ai教程
betazhou28 分钟前
TDSQL-PG创建测试表并定时插入数据模拟生产
前端·javascript·数据库·tdsql·tdsql-pg