WebContainer API
WebContainer API is what does most of the heavy lifting over here. It runs a server within the browser.
WebContainers are a browser-based runtime for executing Node.js applications and operating system commands, entirely inside your browser tab. - Introduction to WebContainers
Installation
Let us install the dependency first. A single dependency is what we need.
Usage
First of all, due to the technology of WebContainer, we have to set up a couple of headers in our vite.config.ts
file.
Setting up Headers
Booting the WebContainer
Let us boot the WebContainer instance in the App
component and store it in the state.
The WebContainer API has its own file system format. So, we will also use the same file system and update our TEMPLATE
to use the same. Do not worry much, and just copy-paste the below code.
We get most of the type safety from TypeScript, and we can use the same to define our template.
WebContainer API also supports directories. But for our use case, we are only
working with files. It does add a lot of complexity to the code, and we are
trying to keep it simple for this course. Also, file systems contents support
Uint8Array
as well. You can consider it as a string. But for this course,
again, we are only working with strings for the file contents.
We will also update the CodeEditor
component to account for these changes.
Alright, you would see an error in the console that we caught about the multiple instances of WebContainer. This is a known issue with the WebContainer API. We have to wait for the issue to be resolved. But for now, we can ignore it.
Mount the filesystem to the WebContainer
Our webContainer
instance currently has no filesystem mounted to it. Let us mount the VITE_REACT_TEMPLATE
to the webContainer
instance.
Great, we have now mounted the files of VITE_REACT_TEMPLATE
to the webContainer
instance.
In the next two sections, we will see wiring up the terminal and the preview section with the WebContainer API.
At this point, our code should match the code in the branch 4-webcontainer-api
.
Last updated on