【Web IDE】WebContainer容器在浏览器中启动运行nodejs并使用vite启动项目

参考了文章WebContainer/api 基础(Web IDE 技术探索 一)

在浏览器中运行vite的vue3项目

示例站点

最终效果

在这里插入图片描述

主要流程

加载WebContainer=》加载代码压缩包=>解压代码压缩包=》生成文件树=》挂载文件树=》pnpm安装依赖=》启动项目

代码

<script setup>
import { onMounted, ref } from 'vue'
import { WebContainer } from "@webcontainer/api";
import { mountZip } from '@/views/Containers/utls.js'
const webUrl = ref("");
const codeZip = '/code/vue-project.zip'
async function initContainer() {
  console.log("挂载")
  // Call only once
  const webcontainerInstance = await WebContainer.boot();
  const nodeV = await webcontainerInstance.spawn("node", ["-v"]);
  nodeV.output.pipeTo(
    new WritableStream({
      write(data) {
        console.log("node -v ==>", data);
      },
    })
  );
  const fileTree =  await mountZip(codeZip)
  console.log('挂载文件',fileTree)
  // 1. 挂载文件
  await webcontainerInstance.mount(fileTree);
  console.log("ls");
  const ls = await webcontainerInstance.spawn("ls", ["-al"]);
  ls.output.pipeTo(
    new WritableStream({
      write(data) {
        console.log(data);
      },
    })
  );
  // 2. 下载依赖
  console.log("pnpm install");
  const install = await webcontainerInstance.spawn("pnpm", ["install"]);
  install.output.pipeTo(
    new WritableStream({
      write(data) {
        console.log(data);
      },
    })
  );
  // 3. 判断exit 状态
  let code = await install.exit;
  if (code !== 0) {
    console.error("error to install.");
  }

  // 4. 启动服务
  console.log("npm run dev");
  const process = await webcontainerInstance.spawn("npm", ["run","dev"]);
  process.output.pipeTo(
    new WritableStream({
      write(data) {
        console.log(data);
      },
    })
  );
  // 5. 监听服务启动
  webcontainerInstance.on("server-ready", (port, url) => {
    console.log("server-ready", url);
    webUrl.value = url;
  });
}


onMounted(() => {
  mountZip(codeZip)
  initContainer()
})
</script>

<template>
<div>
  <iframe :src="webUrl" style="height: 100vh;width: 100%"/>
</div>
</template>

<style scoped>

</style>

工具函数

import JSZip from 'jszip'
export async function  mountZip(zipUrl){
  console.log("读取zip文件",zipUrl)
  const fileTree = {}
  try {
    // 使用 fetch 获取 ZIP 数据
    const response = await fetch(zipUrl);
    const buffer = await response.arrayBuffer();

    // 使用 JSZip 处理获取到的数据
    const zip = new JSZip();
    const zipContents = await zip.loadAsync(buffer);

    // 处理解压后的内容
    for (const [relativePath, file] of Object.entries(zipContents.files)) {
      // console.log('relativePath',relativePath)
      if(file.dir){
        let dirList = relativePath.split('/')
        // console.log('dirList',dirList)
        if(dirList.length > 2){
          let tmp = fileTree
          for (let i = 0; i < dirList.length - 1; i++) {
            // console.log('tmp(dirList[i]',tmp[dirList[i]])
            if(tmp[dirList[i]]){
              tmp = tmp[dirList[i]].directory
            }else{
              tmp[dirList[i]] = {
                directory: {},
              }
            }
          }
        }else{
          fileTree[dirList[0]] = {
            directory: {},
          }
        }
      }else{
        let dirList = relativePath.split('/')
        // console.log('dirList',dirList)
        if(dirList.length > 1) {
          let tmp = fileTree
          for (let i = 0; i < dirList.length - 1; i++) {
            // console.log('tmp(dirList[i]', tmp[dirList[i]])
            if (tmp[dirList[i]]) {
              tmp = tmp[dirList[i]].directory
            } else {
              tmp[dirList[i]] = {
                directory: {},
              }
            }
          }
          // console.log('tmp',tmp)
          tmp[dirList[dirList.length - 1]] = {
            file: {
              contents: await file.async('string')
            },
          }
        }else{
          // console.log('根目录文件',dirList)
          fileTree[dirList[dirList.length - 1]] = {
            file: {
              contents: await file.async('string')
            },
          }
        }
      }
    }
  } catch (error) {
    console.error('获取 ZIP 数据时出错:', error);
  }
  console.log('fileTree',fileTree)
  return fileTree
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飘逸者打瞌睡

如有需要,请私信我。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值