以下是一个在 Bun 环境下使用 TypeScript、React 和 HTMX 开发的简单实例。这个例子创建了一个简单的待办事项列表应用。

首先,确保你已经安装了 Bun。然后,按照以下步骤创建和设置项目:

  1. 创建项目目录并初始化:
mkdir bun-ts-react-htmx-example
cd bun-ts-react-htmx-example
bun init
  1. 安装必要的依赖:
bun add react react-dom htmx.org
bun add -d @types/react @types/react-dom typescript
  1. 创建以下文件结构:
bun-ts-react-htmx-example/
├── src/
│   ├── components/
│   │   └── TodoList.tsx
│   ├── server.ts
│   └── index.tsx
├── public/
│   └── index.html
├── tsconfig.json
└── package.json
  1. 配置 tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ES2020",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "react",
    "esModuleInterop": true
  },
  "include": ["src"]
}
  1. public/index.html 中添加基本 HTML 结构:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bun + TS + React + HTMX Example</title>
    <script src="https://unpkg.com/htmx.org@1.9.2"></script>
</head>
<body>
    <div id="root"></div>
    <script src="/index.js" type="module"></script>
</body>
</html>
  1. src/components/TodoList.tsx 中创建 React 组件:
import React, { useState } from 'react';
 
interface Todo {
  id: number;
  text: string;
}
 
const TodoList: React.FC = () => {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [inputText, setInputText] = useState('');
 
  const addTodo = () => {
    if (inputText.trim()) {
      setTodos([...todos, { id: Date.now(), text: inputText }]);
      setInputText('');
    }
  };
 
  return (
    <div>
      <h1>Todo List</h1>
      <input
        type="text"
        value={inputText}
        onChange={(e) => setInputText(e.target.value)}
      />
      <button onClick={addTodo}>Add Todo</button>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
      <button
        hx-post="/api/refresh-todos"
        hx-target="#htmx-todos"
        hx-swap="innerHTML"
      >
        Refresh Todos (HTMX)
      </button>
      <div id="htmx-todos"></div>
    </div>
  );
};
 
export default TodoList;
  1. src/index.tsx 中设置 React 应用:
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './components/TodoList';
 
ReactDOM.render(
  <React.StrictMode>
    <TodoList />
  </React.StrictMode>,
  document.getElementById('root')
);
  1. 在 `src/server