技能 编程开发 WebContainer与StackBlitz环境配置

WebContainer与StackBlitz环境配置

v20260423
stackblitz-install-auth
本指南详细介绍了如何设置WebContainer API,实现在浏览器端运行Node.js环境。同时,它也提供了集成StackBlitz SDK的方法,用于将高度交互的代码编辑器嵌入到Web应用中。内容涵盖了必要的依赖安装、代码配置以及确保跨域隔离所需的HTTP安全头设置。
获取技能
280 次下载
概览

StackBlitz Install & Auth

Overview

Set up the WebContainer API for running Node.js in the browser, or the StackBlitz SDK for embedding interactive code editors. WebContainers require no auth -- they run entirely client-side. The StackBlitz SDK is for embedding projects from stackblitz.com.

Prerequisites

  • Node.js 18+ for build tooling
  • Modern browser with SharedArrayBuffer support (requires HTTPS + COOP/COEP headers)

Instructions

Step 1: Install WebContainer API

npm install @webcontainer/api

Step 2: Install StackBlitz SDK (for embedding)

npm install @stackblitz/sdk

Step 3: Configure Required HTTP Headers

WebContainers require cross-origin isolation. Add these headers to your server:

// Express middleware
app.use((req, res, next) => {
  res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
  res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
  next();
});
// Vite config
export default defineConfig({
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin',
    },
  },
});

Step 4: Verify WebContainer Boot

import { WebContainer } from '@webcontainer/api';

const wc = await WebContainer.boot();
console.log('WebContainer booted successfully');

// Verify filesystem works
await wc.mount({ 'test.txt': { file: { contents: 'Hello WebContainers!' } } });
const content = await wc.fs.readFile('/test.txt', 'utf-8');
console.log(`File content: ${content}`);

Output

WebContainer booted successfully
File content: Hello WebContainers!

Error Handling

ErrorCauseSolution
SharedArrayBuffer is not definedMissing COOP/COEP headersAdd cross-origin isolation headers
Failed to bootMultiple instancesOnly one WebContainer per page
Not in secure contextHTTP instead of HTTPSUse HTTPS or localhost

Resources

Next Steps

Proceed to stackblitz-hello-world for your first WebContainer project.

信息
分类 编程开发
名称 stackblitz-install-auth
版本 v20260423
大小 2.78KB
更新时间 2026-04-28
语言