基于 WebContainer 的 React Hooks 库,提供了一组用于在 React 应用中使用 WebContainer 的 Hook。
npm install @d8d-webcontainer/react基于 WebContainer 的 React Hooks 库,提供了一组用于在 React 应用中使用 WebContainer 的 Hook。
- 🚀 多终端支持 - 可以创建和管理多个终端实例
- 📁 文件系统操作 - 支持文件浏览、编辑和保存
- 🔄 进程管理 - 支持进程启动、监控和终止
- 🛠 项目初始化 - 支持 git clone、依赖安装等初始化操作
- 🎯 开发服务器检测 - 自动检测和提供开发服务器地址
``bash`
npm install @d8d-webcontainer/react @d8d-webcontainer/api
`tsx
import { useWebContainer, useTerminal, useFileSystem } from '@d8d-webcontainer/react';
function WebContainerDemo() {
// 管理多个终端
const [terminals, setTerminals] = useState([
{ id: 'default', ref: useRef(null) }
]);
// 初始化 WebContainer
const { container, status, error, devServerUrl, activeProcesses } = useWebContainer({
serverUrl: 'http://localhost:3000',
onError: (error) => console.error(error),
});
// 终端操作
const { handleTerminalInput } = useTerminal({
container,
activeProcesses,
onOutput: (data, terminalId) => {
// 将输出发送到对应的终端
const terminal = terminals.find(t => t.id === terminalId);
terminal?.ref.current?.write(data);
},
onError: (error) => console.error(error),
});
// 文件系统操作
const { selectedFile, handleFileSelect, handleFileSave } = useFileSystem({
container,
onStatusChange: (status) => console.log(status),
onError: (error) => console.error(error),
});
// 添加新终端
const addNewTerminal = () => {
const newTerminalId = terminal-${terminals.length + 1};
setTerminals(prev => [...prev, {
id: newTerminalId,
ref: createRef()
}]);
};
return (
Hooks API
$3
初始化和管理 WebContainer 实例。
`typescript
interface UseWebContainerProps {
serverUrl: string;
onError?: (error: Error) => void;
onOutput?: (data: string) => void;
}
interface UseWebContainerReturn {
container: WebContainer | null;
status: string;
error: Error | null;
devServerUrl: string | null;
activeProcesses: Array<{pid: number; command: string; terminalId: string}>;
}
const result = useWebContainer(props: UseWebContainerProps): UseWebContainerReturn;
`$3
管理终端输入输出和进程控制。
`typescript
interface UseTerminalProps {
container: WebContainer | null;
activeProcesses: Array<{pid: number; command: string; terminalId: string}>;
onOutput?: (data: string, terminalId: string) => void;
onError?: (error: Error) => void;
}
interface UseTerminalReturn {
handleTerminalInput: (command: string, terminalId: string) => Promise;
}
const result = useTerminal(props: UseTerminalProps): UseTerminalReturn;
`$3
管理文件系统操作。
`typescript
interface UseFileSystemProps {
container: WebContainer | null;
onStatusChange?: (status: string) => void;
onError?: (error: string) => void;
}
interface UseFileSystemReturn {
handleFileSelect: (path: string, content: string) => void;
handleFileSave: (path: string, content: string) => Promise;
selectedFile: { path: string; content: string } | null;
}
const result = useFileSystem(props: UseFileSystemProps): UseFileSystemReturn;
`注意事项
1. 需要同时安装
@d8d-webcontainer/api 作为依赖
2. WebContainer 服务器需要单独运行
3. 建议在组件卸载时清理 WebContainer 实例
4. 文件路径使用正斜杠 /` 作为分隔符完整的示例项目可以参考:
MIT