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.
We will create a context for the WebContainer API, and to share the context across the application, we will use React's Context API.
The useWebContainer
hook is used to get the context.
Barrel exports the provider.
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.
We will also update the CodeEditor
component to account for these changes.
We are now using the template
from the context. We let the editor know that we are only working with FileNode
. 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. We are only working with strings for now.
Great, there is still a lot of work to be done. But we have made a good start. Let us now update the App
component to use the WebContainerProvider
.
We have wrapped the App
component with the WebContainerProvider
. We have also passed the VITE_REACT_TEMPLATE
to the provider. We are now ready to run the application.
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.
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
.