如果你是一名前端开发者,那么你一定会使用 CodeSandbox 来进行代码编辑、测试以及分享。但是,如果你想使用他们的 API 来嵌入你的应用程序中,那么你就需要使用 npm 包 codesandboxer 了。
在本文中,我们将介绍如何使用 codesandboxer 包来动态创建和嵌入 CodeSandbox 环境,以及如何在本地进行测试和开发。
安装和配置
要开始使用 codesandboxer 包,你需要首先安装它。你可以通过在终端中输入以下命令进行安装:
npm install codesandboxer
一旦你安装了它,你需要一个 codesandbox.json 文件。这个文件包含了与 CodeSandbox 环境相关的配置数据。例如,它可以定义应用程序的依赖关系、入口点等。以下是一个例子:
{ "template": "typescript", "dependencies": { "react": "16.8.6", "react-dom": "16.8.6" } }
当你准备好你的 codesandbox.json 文件之后,你需要将它传递给码盒生成器以创建 CodeSandbox 环境。下面是如何使用 codesandboxer 包创建一个简单的 CodeSandbox:
import { generateSandbox } from 'codesandboxer'; const codesandboxDirectory = '/path/to/codesandbox.json'; const outputDirectory = '/path/to/sandbox-directory'; generateSandbox(codesandboxDirectory, outputDirectory).then(({ sandboxId }) => { console.log(`Created sandbox with id ${sandboxId}`); });
上述代码中,我们传递两个参数:codesandboxDirectory 和 outputDirectory。第一个参数(codesandboxDirectory)是文件的路径(或者是包含了 codesandbox.json 文件的代码仓库的路径)。第二个参数(outputDirectory)是你想要将生成的 CodeSandbox 保存到的路径。一旦代码运行起来,它将会生成一个包含所有文件和依赖项的 CodeSandbox,并返回一个唯一的 sandboxId。
在网页中嵌入 CodeSandbox
在上面的例子中,我们使用 generateSandbox 函数来生成一个 CodeSandbox 。但是,如果你想嵌入它到网页中,你需要使用另一个函数:embedSandbox。下面是一个例子:
import { embedSandbox } from 'codesandboxer'; const sandboxId = 'sandbox-id'; const container = document.getElementById('container'); embedSandbox(sandboxId, container).then((sandbox) => { console.log(`Sandbox with id ${sandboxId} has been embedded into the page`); });
在上述代码中,我们传递了两个参数:sandboxId 和 container。第一个参数(sandboxId)是 CodeSandbox 的唯一标识符。第二个参数(container)是一个 DOM 元素,代表着你想要将 CodeSandbox 嵌入到页面的位置。
一旦代码运行起来,你将会看到一个包含了你的 CodeSandbox 的 iframe 元素嵌入到了页面中。
测试和开发
如果你想在本地测试和开发你的 codesandbox.json 文件,那么你可以使用命令行工具来运行它。下面是一个例子:
npx codesandboxer /path/to/codesandbox.json /path/to/output-directory --preview
在上述代码中,我们使用了 codesandboxer 的命令行工具。
第一个参数是 codesandbox.json 文件的路径。 第二个参数是输出目录的路径。 第三个参数是添加 --preview 标志,以启动一个预览服务器。
预览服务器会启动在 http://localhost:3333 上。当你访问该网址时,你将会看到包含了你的代码的 CodeSandbox。如果你对代码进行了更改,CodeSandbox 将会自动重新构建你的应用程序,并在你保存文件时预览你的更改。
总结
在本文中,我们介绍了如何使用 codesandboxer 包来创建和嵌入 CodeSandbox 环境。我们已经讨论了安装和配置、在网页中嵌入 CodeSandbox 以及测试和开发。现在你已经了解了这个库,你可以开始在你的应用程序中使用 CodeSandbox 进行调试和测试了!
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/70756