【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
}
相关推荐
kyriewen1 小时前
我把今年流传的前端 AI 面试题整理了一遍——4 类场景题+回答框架(附速查表)
前端·面试·程序员
计算机魔术师1 小时前
国产多模态模型正面硬刚Opus旗舰:差距从30%缩到3%
前端
风骏时光牛马1 小时前
程序员进阶:深度思考,解锁职场成长的底层逻辑
前端
IT_陈寒2 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
爱丶不疚2 小时前
Eval: Agent 说的 Eval 是什么?从单测、TDD 到 Sentry 聊起
前端·ai编程·vibecoding
求道於盲2 小时前
python中的类型标注
前端
计算机魔术师2 小时前
从硅谷测试到全球铺开,ChatGPT广告的10亿美元秘密
前端
专业抄代码选手3 小时前
08|Fiber 上的 `useState`:状态终于属于具体组件
前端·javascript·react.js
默_笙4 小时前
😭 Vibe Coding 翻车实录:AI 编程为什么必须先写"剧本"
前端·javascript
LEE4 小时前
原来 Claude Code 最厉害的工具,一行代码都不写
前端·后端