What is @codesandbox/sandpack-client?
@codesandbox/sandpack-client is a client library for embedding and interacting with Sandpack, a tool that allows you to run and manage code sandboxes directly in your web applications. It provides a way to programmatically control sandboxes, execute code, and retrieve results, making it useful for educational tools, live coding environments, and interactive documentation.
What are @codesandbox/sandpack-client's main functionalities?
Creating a Sandpack Client
This feature allows you to create a new Sandpack client instance by providing an iframe element and a configuration object. The configuration includes the files and template to be used in the sandbox.
const { SandpackClient } = require('@codesandbox/sandpack-client');
const iframe = document.getElementById('sandpack-iframe');
const client = new SandpackClient(iframe, { files: { '/index.js': { code: 'console.log("Hello, Sandpack!");' } }, template: 'node' });
Running Code
This feature allows you to run the code inside the sandbox. After creating the Sandpack client, you can call the `run` method to execute the code.
client.run();
Listening to Events
This feature allows you to listen to events from the sandbox. You can use the `listen` method to handle messages such as logs, errors, and other events emitted by the sandbox.
client.listen((message) => { console.log('Received message:', message); });
Updating Files
This feature allows you to update the content of a file in the sandbox. You can use the `updateFile` method to change the code of a specific file.
client.updateFile('/index.js', 'console.log("Updated code!");');
Other packages similar to @codesandbox/sandpack-client
codesandbox
The `codesandbox` package provides a way to interact with CodeSandbox programmatically. It allows you to create, update, and manage sandboxes, similar to @codesandbox/sandpack-client. However, it is more focused on the overall management of sandboxes rather than embedding and interacting with them directly in web applications.
Sandpack client
This is a small foundation package that sits on top of the bundler. It is
framework agnostic and facilitates the handshake between your context and the bundler iframe.
import { loadSandpackClient } from "@codesandbox/sandpack-client";
const main = async () => {
const client = await loadSandpackClient("#preview", {
files: {
"/index.js": {
code: `console.log(require('uuid'))`,
},
},
entry: "/index.js",
dependencies: {
uuid: "latest",
},
});
}
Read more