快速入门:连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 页面。

相关推荐
ai小鬼头14 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Alfred king23 分钟前
面试150 生命游戏
leetcode·游戏·面试·数组
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim1 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim1 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
aha-凯心1 小时前
vben 之 axios 封装
前端·javascript·学习
遗憾随她而去.1 小时前
uniapp 中使用路由导航守卫,进行登录鉴权
前端·uni-app
xjt_09012 小时前
浅析Web存储系统
前端
一只叫煤球的猫2 小时前
手撕@Transactional!别再问事务为什么失效了!Spring-tx源码全面解析!
后端·spring·面试
foxhuli2292 小时前
禁止ifrmare标签上的文件,实现自动下载功能,并且隐藏工具栏
前端