JSPM

  • Created
  • Published
  • Downloads 60605
  • Score
    100M100P100Q156092F
  • License UNLICENSED

WebContainer Public API

Package Exports

  • @webcontainer/api
  • @webcontainer/api/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@webcontainer/api) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

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 { load } from '@webcontainer/api';

// call this only once
async function bootWhenReady() {
  // `load` should only be called once
  const WebContainer = await load();

  // 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.loadFiles(projectFiles);
}

async function startDevServer() {
  const install = await webcontainer.run(
    {
      command: 'npm',
      args: ['i'],
    },
    {
      output(data: string) {
        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(
    {
      command: 'npm',
      args: ['run', 'dev'],
    },
    {
      output(data: string) {
        console.log(`[dev server] ${data}`);
      },
    }
  );
}

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.