JSPM

  • Created
  • Published
  • Downloads 67560
  • Score
    100M100P100Q150099F
  • License MIT

WebContainer Public API

Package Exports

  • @webcontainer/api

Readme

WebContainer Public API

This is an alpha project, not ready for general consumption. Expect breaking changes left and right!

If you want to get early access to the WebContainer Public API, please contact StackBlitz.

How To

The API surface is small yet, so make sure to check index.d.ts.

Cross-Origin Isolation

WebContainer requires SharedArrayBuffer to function. In turn, this requires your website to be cross-origin isolated. Among other things, the root document must be served with:

Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin

You can check our article on the subject and our docs on browser support for more details.

Quickstart

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

// call this only once
async function bootWhenReady() {
  // only a single instance of WebContainer can be created
  const webcontainer = await WebContainer.boot();

  return webcontainer;
}

// elsewhere...
import type { FileSystemTree } from '@webcontainer/api';

// you'll need to "copy" your project files into the file system
async function initProject(projectFiles: FileSystemTree) {
  return await webcontainer.mount(projectFiles);
}

async function startDevServer() {
  const install = await webcontainer.spawn('npm', ['i']);

  install.output.pipeTo(new WritableStream({
    write(data) {
      console.log(`[npm install] ${data}`);
    }
  }));

  const installExitCode = await install.onExit();

  if (installExitCode !== 0) {
    throw new Error('Unable to run npm install');
  }

  return await webcontainer.run('npm', ['run', 'dev']);
}

Troubleshooting

Cookie blockers, either from third-party addons or built-in into the browser, can prevent WebContainer from running correctly. Check the on('error') event and our docs.

License

Copyright 2022 StackBlitz, Inc.