Building Preview
Let us build out a preview for our live changes
Setting up Preview component
Create a new file called Preview.tsx
and the respective barrel file index.ts
in the src/components/Preview
directory.
Barrel export the file.
We can now import the Preview
component in the App.tsx
file and render it.
Using iframe for Preview
We need a truly dynamic preview component that can render any HTML content. iframe
elements help achieve this. Let's update the Preview
component to use an iframe.
We need to create a new file called loading.html
at the root of our project. This file will be used to display a loading message while the preview is being loaded.
Wiring up the Preview component with WebContainer API
We need to update the Preview
component to listen to the webContainer
context and update the iframe content accordingly.
We get a server-ready
event from the webContainer
context when the server is ready to serve the preview content. We can listen to this event and update the iframe content.
Now, run the dev server through the terminal we built earlier and see the preview in action.
Updating the Preview on code changes
But, we can see that the preview is not updating when we make changes to the code. We need to update the webContainer
to serve the updated content when the code changes.
By writing to the WebContainer API's file system, we can update the preview content when the code changes. The Monaco editor's onChange
event triggers the handleCodeChange
function, which writes the updated content to the file system.
Now, you should see the preview updating as you make changes to the code.
At this point, our code should match the code in the branch 6-building-preview
.