### Run npm install and Dev Server Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/quickstart.md Illustrates how to spawn processes within the WebContainer to install dependencies using 'npm install' and then start the development server with 'npm run dev'. It includes error handling for the install process. ```javascript async function startDevServer() { const installProcess = await webcontainerInstance.spawn('npm', ['install']); const installExitCode = await installProcess.exit; if (installExitCode !== 0) { throw new Error('Unable to run npm install'); } // `npm run dev` await webcontainerInstance.spawn('npm', ['run', 'dev']); } ``` -------------------------------- ### Install WebContainer API Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/quickstart.md Installs the WebContainer API package using npm. This is the first step to integrate the API into your project. ```bash npm i @webcontainer/api ``` -------------------------------- ### Navigate and Run Vite App Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/1-build-your-first-webcontainer-app.md Commands to navigate into the created app directory, install project dependencies, and start the local development server. This prepares the Vite app for preview. ```bash cd webcontainers-express-app npm install npm run dev ``` -------------------------------- ### Develop Locally with npm Source: https://github.com/stackblitz/webcontainer-docs/blob/main/README.md Steps to install project dependencies and start the documentation site in development mode using npm. ```sh npm install npm run dev ``` -------------------------------- ### Initialize Terminal and WebContainer in main.js Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/6-connect-a-terminal.md This snippet sets up the Terminal instance and opens it in the DOM. It then boots the WebContainer, mounts the project files, installs dependencies, and starts the development server, passing the terminal instance to these processes for output redirection. ```javascript window.addEventListener('load', async () => { textareaEl.value = files['index.js'].file.contents; textareaEl.addEventListener('input', (e) => { writeIndexJS(e.currentTarget.value); }); const terminal = new Terminal({ convertEol: true, }); terminal.open(terminalEl); // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); const exitCode = await installDependencies(terminal); if (exitCode !== 0) { throw new Error('Installation failed'); }; startDevServer(terminal); }); ``` -------------------------------- ### Setup WebContainer and Server Ready Listener Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/7-add-interactivity.md Initializes the WebContainer, mounts the project files, and sets up a listener for the 'server-ready' event. This event is crucial for updating the application's preview when the server starts. ```js window.addEventListener('load', async () => { textareaEl.value = files['index.js'].file.contents; textareaEl.addEventListener('input', (e) => { writeIndexJS(e.currentTarget.value); }); const terminal = new Terminal({ convertEol: true, }); terminal.open(terminalEl); // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { iframeEl.src = url; }); }); ``` -------------------------------- ### Initialize WebContainer and Start Dev Server on Load (JavaScript) Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/4-running-dev-server.md This JavaScript code sets up an event listener for the `window.load` event. It initializes the WebContainer, mounts the application files, installs dependencies, and then calls `startDevServer()` to launch the development server. This ensures the server starts only after the page and dependencies are ready. ```javascript window.addEventListener('load', async () => { textareaEl.value = files['index.js'].file.contents; // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); const exitCode = await installDependencies(); if (exitCode !== 0) { throw new Error('Installation failed'); }; startDevServer(); }); ``` -------------------------------- ### Create WebContainer Instance Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/quickstart.md Demonstrates how to create a WebContainer instance by importing the WebContainer class and calling the boot method. The boot method should only be called once. ```javascript import { WebContainer } from '@webcontainer/api'; // Call only once const webcontainerInstance = await WebContainer.boot(); ``` -------------------------------- ### Start Dev Server with WebContainer Events Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/running-processes.md Illustrates how to start a development server using 'npm run start' and listen for the 'server-ready' event. This event is emitted when the server is ready to accept requests, providing the port and URL. ```javascript async function startDevServer() { // Run `npm run start` to start the Express app await webcontainerInstance.spawn('npm', ['run', 'start']); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { // ... handle server ready event }); } ``` -------------------------------- ### Install WebContainer API Package Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Installs the official WebContainer API package from npm into your project. This package provides the necessary tools to interact with and manage WebContainer instances. ```bash npm i @webcontainer/api ``` -------------------------------- ### Preview Application URL Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/quickstart.md Explains how to capture the URL of the running development server from the 'server-ready' event and use it to display the application in an iframe. ```javascript webcontainerInstance.on('server-ready', (port, url) => (iframeEl.src = url)); ``` -------------------------------- ### Open WebContainer Starter Project Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/introduction.md Provides a direct link to open the WebContainer starter project in StackBlitz. This allows users to quickly begin experimenting with the WebContainer API without manual setup. ```html Open in StackBlitz ``` -------------------------------- ### Mount Project Files Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/quickstart.md Shows how to load project files into the WebContainer's file system using the mount method. This is recommended for optimal performance, especially on page load. ```javascript await webcontainerInstance.mount(projectFiles); ``` -------------------------------- ### Call installDependencies and handle errors Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/3-installing-dependencies.md Example of calling the `installDependencies` function and handling potential errors based on the exit code. This code snippet is typically placed within an event listener for application startup. ```js window.addEventListener('load', async () => { textareaEl.value = files['index.js'].file.contents; // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); const exitCode = await installDependencies(); if (exitCode !== 0) { throw new Error('Installation failed'); }; }); ``` -------------------------------- ### WebContainer API Starter Example Source: https://github.com/stackblitz/webcontainer-docs/blob/main/README.md Provides direct links to explore the WebContainer API. The StackBlitz link opens a pre-configured environment for immediate interaction, while the Codeflow link points to a starter project for local development. ```APIDOC WebContainer API Starter: - StackBlitz: https://webcontainer.new - Description: Opens the WebContainer API in a StackBlitz editor for immediate exploration. - Codeflow IDE: https://pr.new/github.com/stackblitz/webcontainer-api-starter - Description: Opens the WebContainer API starter project in the Codeflow IDE for local development. ``` -------------------------------- ### Spawn npm install command in WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/3-installing-dependencies.md Executes the `npm install` command within a WebContainer instance. This is a fundamental operation for setting up project dependencies. The `spawn` method takes the command and its arguments as separate parameters. ```js webcontainerInstance.spawn('npm', ['install']); ``` -------------------------------- ### Redirect npm install Output to Terminal Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/6-connect-a-terminal.md This function takes a Terminal instance and spawns the `npm install` process. It pipes the process's output to the terminal's `write` method, displaying installation progress and results directly in the application's terminal UI. ```javascript /** * @param {Terminal} terminal */ async function installDependencies(terminal) { // Install dependencies const installProcess = await webcontainerInstance.spawn('npm', ['install']); installProcess.output.pipeTo(new WritableStream({ write(data) { terminal.write(data); } })) // Wait for install command to exit return installProcess.exit; } ``` -------------------------------- ### JavaScript FileSystemTree Example Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/api.md Provides an example of creating a FileSystemTree object to define project structure, including files with content, symlinks, and empty directories. ```js const tree = { myproject: { directory: { 'foo.js': { file: { contents: 'const x = 1;' } }, 'bar.js': { file: { symlink: './foo.js' } }, '.envrc': { file: { contents: 'ENVIRONMENT=staging' } }, } }, emptyFolder: { directory: {} }, }; ``` -------------------------------- ### Install Dependencies with WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/running-processes.md An asynchronous function that spawns an 'npm install' process and waits for it to complete. It returns the exit code of the installation process, indicating success or failure. ```javascript async function installDependencies() { // Install dependencies const installProcess = await webcontainerInstance.spawn('npm', ['install']); // Wait for install command to exit return installProcess.exit; } ``` -------------------------------- ### Spawn cd command in WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/3-installing-dependencies.md Demonstrates spawning a 'cd' command to change directories within the WebContainer. It shows how to pass a single argument to the `spawn` method. ```bash cd hello-world ``` ```js webcontainerInstance.spawn('cd', ['hello-world']); ``` -------------------------------- ### Express App Package.json Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Specifies the dependencies and scripts for the Express application. It includes 'express' and 'nodemon' as dependencies and defines a 'start' script to run the application using nodemon for auto-reloading. ```json { "name": "example-app", "type": "module", "dependencies": { "express": "latest", "nodemon": "latest" }, "scripts": { "start": "nodemon --watch './' index.js" } } ``` -------------------------------- ### Vue Script Setup for Angular Tutorial Page Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/angular-tutorial.md This script setup block is used within a Vue.js component to import necessary helper components for rendering the Angular tutorial page. It imports `PageHeading` and `Screenshot` components, which are likely used to display the page title and associated images or links. ```typescript import PageHeading from '@theme/components/Helpers/CommunityProjectPageHeading.vue'; import Screenshot from '@theme/components/Helpers/Screenshot.vue'; ``` -------------------------------- ### Stream output from a spawned process Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/3-installing-dependencies.md Demonstrates how to capture and stream the output from a process running inside a WebContainer. The `output` property of the spawned process can be piped to a `WritableStream` to log output in real-time. ```js const installProcess = await webcontainerInstance.spawn('npm', ['install']); installProcess.output.pipeTo(new WritableStream({ write(data) { console.log(data); } })); ``` -------------------------------- ### Spawn ls command with arguments in WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/3-installing-dependencies.md Illustrates spawning the 'ls' command with multiple arguments, such as a directory and a flag (`-l`). This showcases how to pass an array of arguments to the `spawn` method for more complex commands. ```bash ls src -l ``` ```js webcontainerInstance.spawn('ls', ['src', '-l']); ``` -------------------------------- ### Vue.js TypeScript Setup for StackBlitz Web Publisher Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/stackblitz-web-publisher.md This script setup block defines the components and data used for the StackBlitz Web Publisher community project page. It imports necessary Vue components like PageHeading, Screenshot, VideoLink, and AttributionLinks, and also imports people data to display attribution. ```typescript ``` -------------------------------- ### Redirect npm run start Output to Terminal Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/6-connect-a-terminal.md This function spawns the `npm run start` process for the development server. It pipes the process's output to the terminal's write function and listens for the `server-ready` event to update the iframe source. ```javascript /** * @param {Terminal} terminal */ async function startDevServer(terminal) { // Run `npm run start` to start the Express app const serverProcess = await webcontainerInstance.spawn('npm', [ 'run', 'start', ]); serverProcess.output.pipeTo( new WritableStream({ write(data) { terminal.write(data); }, }) ); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { iframeEl.src = url; }); } ``` -------------------------------- ### Configure Cross-Origin Isolation Headers Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/quickstart.md Specifies the necessary COOP/COEP headers required for WebContainers to function, as they rely on SharedArrayBuffer. These headers ensure the website is cross-origin isolated. ```yaml Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Opener-Policy: same-origin ``` -------------------------------- ### VSLite Vue Component Setup Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/vslite.md This snippet demonstrates the setup for the VSLite project page using Vue.js with TypeScript. It imports necessary components for page headings and screenshots, and includes the main content describing the IDE's features. ```vue A lighweight IDE-like experience with a fresh Node.js environment for you to play with. Use terminal and write code using autocomplete-enabled editor: ``` -------------------------------- ### Vue Component Setup Script Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/clack.md This script sets up the Vue component for the clack project page, importing necessary helpers like PageHeading and Screenshot. ```ts import PageHeading from '@theme/components/Helpers/CommunityProjectPageHeading.vue'; import Screenshot from '@theme/components/Helpers/Screenshot.vue'; ``` -------------------------------- ### Vue Component Setup Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/otto-engineer.md This snippet sets up a Vue 3 component using the Composition API with TypeScript. It imports and uses helper components like PageHeading and Screenshot to structure the page content. The setup function is where component logic and imports are declared. ```vue ``` -------------------------------- ### Run Dev Server and Listen for `server-ready` in WebContainers (JavaScript) Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/4-running-dev-server.md This JavaScript function `startDevServer` spawns the development server using `npm run start` within a WebContainer. It then listens for the `server-ready` event, which provides the server's URL, and assigns this URL to an iframe element to display the running application. ```javascript async function startDevServer() { // Run `npm run start` to start the Express app await webcontainerInstance.spawn('npm', ['run', 'start']); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { iframeEl.src = url; }); } ``` -------------------------------- ### Vue Component Setup (TypeScript) Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/schachnovelle.md This script sets up the Vue component for the project page. It imports `PageHeading` and `Screenshot` components, which are used to display project information and visuals. ```typescript import PageHeading from '@theme/components/Helpers/CommunityProjectPageHeading.vue'; import Screenshot from '@theme/components/Helpers/Screenshot.vue'; ``` -------------------------------- ### WebContainer File System Operations (fs) Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/working-with-the-file-system.md Provides an overview and usage examples for core file system operations exposed by the WebContainer instance's `fs` property. This includes reading files, listing directory contents, removing files/directories, writing files, and creating directories. ```APIDOC WebContainerInstance.fs: Provides methods for interacting with the WebContainer's file system. Methods: - readFile(path: string, encoding?: string): Promise Reads the content of a file at the specified path. Returns a UInt8Array by default, or a string if an encoding is provided. Example: const fileContent = await webcontainerInstance.fs.readFile('/package.json', 'utf-8'); - readdir(path: string, options?: { withFileTypes?: boolean, encoding?: string }): Promise Reads a directory and returns an array of its entries. Can return an array of strings (names) or Dirent objects if `withFileTypes` is true. Dirent object properties: - name: string - isFile(): boolean - isDirectory(): boolean Example: const entries = await webcontainerInstance.fs.readdir('/src', { withFileTypes: true }); - rm(path: string, options?: { recursive?: boolean, force?: boolean }): Promise Removes a file or directory. Use `recursive: true` for directories. - writeFile(path: string, data: string | Buffer | ArrayBuffer | UInt8Array, options?: { encoding?: string }): Promise Writes data to a file. Creates the file if it does not exist, or overwrites it if it does. - mkdir(path: string, options?: { recursive?: boolean }): Promise Creates a directory. Use `recursive: true` to create parent directories as needed. ``` -------------------------------- ### Loading a Single File into WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/working-with-the-file-system.md This example shows how to load a single file, 'package.json', into the WebContainer's file system using the `mount` method. The `files` object must conform to the `FileSystemTree` structure. ```javascript /** @type {import('@webcontainer/api').FileSystemTree} */ const files = { 'package.json': { file: { contents: ` { "name": "vite-starter", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "devDependencies": { "vite": "^4.0.4" } }`, }, }, }; await webcontainerInstance.mount(files); ``` -------------------------------- ### TypeScript Setup Script Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/index.md This script block imports necessary Vue components and data from theme modules. It sets up the environment for the Home component, preparing it with external data for rendering. ```typescript import Home from '@theme/components/Home.vue'; import { footerSections } from '@theme/data/links'; ``` -------------------------------- ### Vue Script Setup for Stylelint Playground Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/stylelint-playground.md This script sets up the Stylelint Playground page using Vue.js. It imports necessary components like PageHeading and Screenshot, and configures the page heading with a title and category. ```ts With Stylelint playground you can experiment with rulesets defined in different npm packages by specifying them in package.json! They are actually being installed – just as they would in your project ``` -------------------------------- ### Install dependencies and get exit code Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/3-installing-dependencies.md A function to install project dependencies using `npm install` and return the exit code of the process. An exit code of 0 indicates successful execution. ```js async function installDependencies() { // Install dependencies const installProcess = await webcontainerInstance.spawn('npm', ['install']); // Wait for install command to exit return installProcess.exit; } ``` -------------------------------- ### Boot WebContainer Instance Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Initializes and boots a WebContainer instance using the WebContainer API. This code should be placed in your main application file (e.g., main.js) and is typically executed once when the window loads. ```js import { WebContainer } from '@webcontainer/api'; /** @type {import('@webcontainer/api').WebContainer} */ let webcontainerInstance; window.addEventListener('load', async () => { // Call only once webcontainerInstance = await WebContainer.boot(); }); ``` -------------------------------- ### Boot and Mount Files in WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Initializes the WebContainer environment and mounts a set of files into its virtual file system. This is a foundational step for running applications within the WebContainer. It requires the '@webcontainer/api' library. ```js import './style.css'; import { WebContainer } from '@webcontainer/api'; import { files } from './files'; /** @type {import('@webcontainer/api').WebContainer} */ let webcontainerInstance; window.addEventListener('load', async () => { // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); }); ``` -------------------------------- ### Initialize Vite App Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/1-build-your-first-webcontainer-app.md Command to create a new Vite app using the vanilla JavaScript template. This sets up the basic project structure for the tutorial. ```bash npm create vite webcontainers-express-app --template vanilla ``` -------------------------------- ### Install Xterm.js Fit Addon Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/7-add-interactivity.md Installs the necessary addon for Xterm.js to handle terminal resizing and fitting to its container element. ```bash npm install @xterm/addon-fit ``` -------------------------------- ### Install Xterm.js via npm Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/6-connect-a-terminal.md Installs the Xterm.js library, a terminal frontend component used by VS Code and other web-based IDEs, using npm. This is a prerequisite for adding terminal functionality. ```bash npm install @xterm/xterm ``` -------------------------------- ### Vue SFC Setup with TypeScript Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/stackblitz-codeflow.md This snippet demonstrates the setup of a Vue Single File Component using TypeScript. It imports necessary components and data, including specific person data, for rendering the page content. ```typescript import PageHeading from '@theme/components/Helpers/CommunityProjectPageHeading.vue'; import Screenshot from '@theme/components/Helpers/Screenshot.vue'; import ArticleLink from '@theme/components/Helpers/ArticleLink.vue'; import VideoLink from '@theme/components/Helpers/VideoLink.vue'; import AttributionLinks from '@theme/components/Helpers/AttributionLinks.vue'; import { people } from '@theme/data/people'; const { ERIC_SIMONS } = people; ``` -------------------------------- ### Express App Entry Point Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Defines a basic Express.js server that listens on port 3111 and responds with a welcome message to root requests. This serves as the main application file to be run inside the WebContainer. ```js import express from 'express'; const app = express(); const port = 3111; app.get('/', (req, res) => { res.send('Welcome to a WebContainers app! 🥳'); }); app.listen(port, () => { console.log(`App is live at http://localhost:${port}`); }); ``` -------------------------------- ### Define Filesystem Tree for WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Creates a JavaScript object representing the filesystem structure to be mounted within the WebContainer. It includes the application's entry point (index.js) and its package.json, with their contents defined as strings. ```js /** @satisfies {import('@webcontainer/api').FileSystemTree} */ export const files = { 'index.js': { file: { contents: ` import express from 'express'; const app = express(); const port = 3111; app.get('/', (req, res) => { res.send('Welcome to a WebContainers app! 🥳'); }); app.listen(port, () => { console.log(`App is live at http://localhost:${port}`); });`, }, }, 'package.json': { file: { contents: ` { "name": "example-app", "type": "module", "dependencies": { "express": "latest", "nodemon": "latest" }, "scripts": { "start": "nodemon --watch './' index.js" } }`, }, }, }; ``` -------------------------------- ### Generate and Mount Binary Snapshots Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/working-with-the-file-system.md Explains how to create a binary snapshot of a local folder using `@webcontainer/snapshot` and then mount this snapshot into a WebContainer instance on the client-side. This is useful for deploying existing project structures. ```typescript import { snapshot } from '@webcontainer/snapshot'; // Server-side: Generate snapshot const folderSnapshot = await snapshot(SOURCE_CODE_FOLDER); // Server-side: Serve snapshot (e.g., Express) app.get('/snapshot', (req, res) => { res .setHeader('content-type', 'application/octet-stream') .send(snapshot); }); // Client-side: Fetch and mount snapshot import { WebContainer } from '@webcontainer/api'; const webcontainer = await WebContainer.boot(); const snapshotResponse = await fetch('/snapshot'); const snapshot = await snapshotResponse.arrayBuffer(); await webcontainer.mount(snapshot); ``` -------------------------------- ### Import Filesystem Tree in Main Application Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md Imports the previously defined filesystem tree object from './files.js' into the main application file (main.js). This makes the file structure available for mounting into the WebContainer instance. ```js import { files } from './files'; ``` -------------------------------- ### WebContainer boot() method Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/api.md Boots a WebContainer instance. This static method takes optional BootOptions to configure cross-origin isolation, working directory name, and preview error forwarding. It returns a Promise resolving to a WebContainer instance. ```APIDOC WebContainer: static boot(options: BootOptions = {}): Promise - Boots a WebContainer instance. - Parameters: - options: BootOptions (optional) - Configuration for booting. - coep?: 'require-corp' | 'credentialless' | 'none' - Value for the COEP header. - workdirName?: string - Sets the folder name for the working directory. - forwardPreviewErrors?: boolean | 'exceptions-only' - Configure forwarding of errors from preview iframes. - Returns: Promise - A Promise that resolves to a WebContainer instance. BootOptions: interface BootOptions { coep?: 'require-corp' | 'credentialless' | 'none'; workdirName?: string; forwardPreviewErrors?: boolean | 'exceptions-only'; } Example Usage: webcontainerInstance.on('preview-message', (message) => { // process the message received from a preview }); ``` -------------------------------- ### JavaScript Directory Watch Example with Recursion Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/api.md Shows how to watch a directory recursively for file system changes. The callback logs the event type and the filename. ```js webcontainerInstance.fs.watch('/src', { recursive: true }, (event, filename) => { console.log(`file: ${filename} action: ${event}`); }); ``` -------------------------------- ### JavaScript File System Watch Example Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/api.md Demonstrates how to use the `webcontainerInstance.fs.watch` method to monitor a specific file for changes. The callback logs the event type. ```js webcontainerInstance.fs.watch('/src/main.js', (event) => { console.log(`action: ${event}`); }); ``` -------------------------------- ### Read and Log File Content from WebContainer Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/2-setting-up-webcontainers.md After mounting files, this snippet demonstrates how to read the content of a specific file (e.g., 'package.json') from the WebContainer's file system using the `fs.readFile` method. The content is then logged to the console for verification. This requires an active WebContainer instance. ```js window.addEventListener('load', async () => { // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); const packageJSON = await webcontainerInstance.fs.readFile('package.json', 'utf-8'); console.log(packageJSON); }); ``` -------------------------------- ### SvelteKit Browser Learning Experience Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/sveltekit.md This Svelte component provides an educational experience for learning Svelte in the browser using the WebContainer API. It displays a page heading, a descriptive text with a link to try the tutorial, a screenshot of the SvelteKit interface, and a video link to a talk by Rich Harris. ```Svelte A full educational experience of learning Svelte in the browser. [Try it yourself!](https://learn.svelte.dev/tutorial/welcome-to-svelte) ``` -------------------------------- ### Update main.js Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/1-build-your-first-webcontainer-app.md Replaces the content of the `main.js` file to create a minimalistic app structure. This involves importing a CSS file and setting up the main application element. ```javascript import './style.css'; document.querySelector('#app').innerHTML = ``; ``` -------------------------------- ### Start Shell Process with jsh Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/7-add-interactivity.md Defines a function to spawn the 'jsh' shell within the WebContainer environment. It pipes the shell's output stream to the provided Xterm.js terminal instance for display. ```js /** * @param {Terminal} terminal */ async function startShell(terminal) { const shellProcess = await webcontainerInstance.spawn('jsh'); shellProcess.output.pipeTo( new WritableStream({ write(data) { terminal.write(data); }, }) ); return shellProcess; }; ``` -------------------------------- ### Spawn Command in WebContainers Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/guides/running-processes.md Demonstrates the basic usage of the `spawn` method to execute commands within a WebContainer instance. It takes the command name and an array of arguments. Optional spawn options can also be provided. ```javascript webcontainerInstance.spawn('npm', ['install']); ``` ```javascript webcontainerInstance.spawn('ls', ['src', '-l']); ``` -------------------------------- ### Vue.js Script Setup Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/community-projects/builder-io-playground.md Sets up the Vue.js component with necessary imports for PageHeading and Screenshot components. This block utilizes TypeScript for type safety and modern JavaScript features within the Vue framework. ```typescript import PageHeading from '@theme/components/Helpers/CommunityProjectPageHeading.vue'; import Screenshot from '@theme/components/Helpers/Screenshot.vue'; ``` -------------------------------- ### Vue Component Setup with TypeScript Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/ai.md Sets up a Vue 3 component using TypeScript, importing necessary components and data for rendering. This block defines the script logic for the page. ```typescript import AiPage from '@theme/components/Ai.vue'; import { footerSections } from '@theme/data/links'; ``` -------------------------------- ### Integrate Shell Startup into Event Listener Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/7-add-interactivity.md Calls the `startShell` function after the WebContainer has booted and mounted files, integrating the shell functionality into the application's startup sequence. ```js window.addEventListener('load', async () => { textareaEl.value = files['index.js'].file.contents; textareaEl.addEventListener('input', (e) => { writeIndexJS(e.currentTarget.value); }); const terminal = new Terminal({ convertEol: true, }); terminal.open(terminalEl); // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { iframeEl.src = url; }); startShell(terminal); }); ``` -------------------------------- ### Initialize and Use Xterm.js FitAddon Source: https://github.com/stackblitz/webcontainer-docs/blob/main/docs/tutorial/7-add-interactivity.md Imports the FitAddon, creates an instance, loads it into the terminal, and calls the fit() method to ensure the terminal correctly adjusts its dimensions to the available space. ```js import { FitAddon } from '@xterm/addon-fit'; window.addEventListener('load', async () => { textareaEl.value = files['index.js'].file.contents; textareaEl.addEventListener('input', (e) => { writeIndexJS(e.currentTarget.value); }); const fitAddon = new FitAddon(); const terminal = new Terminal({ convertEol: true, }); terminal.loadAddon(fitAddon); terminal.open(terminalEl); fitAddon.fit(); // Call only once webcontainerInstance = await WebContainer.boot(); await webcontainerInstance.mount(files); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { iframeEl.src = url; }); startShell(terminal); }); ```