技能 编程开发 嵌入交互式代码沙盒与演示

嵌入交互式代码沙盒与演示

v20260423
stackblitz-core-workflow-b
使用StackBlitz SDK,可以轻松地将实时、交互式的代码沙盒(WebContainer)嵌入到文档、博客或教程中。这种功能允许用户在不离开当前页面的情况下,直接查看和实验代码示例(如React、TypeScript),极大地提升了教程和文档的互动性和实战性。支持从GitHub仓库嵌入或创建内联项目。
获取技能
109 次下载
概览

StackBlitz Core Workflow B: Embedding & Sharing

Overview

Embed interactive StackBlitz projects in documentation, blog posts, and tutorials using the StackBlitz SDK. Supports embedding from GitHub repos, existing StackBlitz projects, or inline code.

Instructions

Step 1: Embed from GitHub

import sdk from '@stackblitz/sdk';

// Embed a GitHub repo as an interactive editor
sdk.embedGithubProject('embed-container', 'vitejs/vite/packages/create-vite/template-react-ts', {
  openFile: 'src/App.tsx',
  height: 500,
  theme: 'dark',
  clickToLoad: true,  // Don't load until user clicks
});

Step 2: Embed Inline Project

sdk.embedProject('embed-container', {
  title: 'React Counter Demo',
  template: 'node',
  files: {
    'src/App.tsx': `
import { useState } from 'react';
export default function App() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>;
}`,
    'package.json': JSON.stringify({
      dependencies: { react: '^18', 'react-dom': '^18' },
    }),
  },
}, {
  openFile: 'src/App.tsx',
  terminalHeight: 25,
});

Step 3: Open in New Tab

// Open project in full StackBlitz editor
sdk.openGithubProject('user/repo', { openFile: 'README.md' });

// Open inline project
sdk.openProject({
  title: 'Quick Demo',
  template: 'node',
  files: { 'index.js': 'console.log("Hello!")' },
});

Step 4: URL-Based Embedding

<!-- iframe embed (no SDK needed) -->
<iframe
  src="https://stackblitz.com/edit/vitejs-vite?embed=1&file=src/main.ts&theme=dark"
  style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden;"
></iframe>

<!-- GitHub repo embed -->
<iframe
  src="https://stackblitz.com/github/user/repo?embed=1&file=README.md"
  style="width:100%;height:500px;border:0;"
></iframe>

Error Handling

Error Cause Solution
Embed shows loading forever Missing template files Ensure package.json is included
clickToLoad not working SDK version mismatch Update @stackblitz/sdk
GitHub embed 404 Wrong repo path Use owner/repo/path/to/subdir format

Resources

Next Steps

For common errors, see stackblitz-common-errors.

信息
Category 编程开发
Name stackblitz-core-workflow-b
版本 v20260423
大小 3.01KB
更新时间 2026-04-28
语言