一、问题如下:
Couldn't connect to server
This means sandpack cannot connect to the runtime or your network is having some issues. Please check the network tab in your browser and try again. If the problem persists, report it via [email](mailto:hello@codesandbox.io?subject=Sandpack%20Timeout%20Error) or submit an issue on [GitHub.](https://github.com/codesandbox/sandpack/issues)
ENV: create-react-app
ERROR: TIME_OUT
二、背景
在我的毕设中,使用的是nextjs框架。我希望像claude一样左边聊天,右边生成代码,专业词叫做交互式编辑器。经过询问claude3.7发现@codesandbox/sandpack-react这个库特别好用,样式也喜欢,效果如下:
但是,只有本地能运行,如果你跟我一样部署到服务器你会发现,报开头一样的错:
这个时候,我就去到该库的github源代码的issues处,翻遍很多条类似的问题仍旧找不到答案,所以只能从原理出发。
三、原因:Babel构建错误
通过分析控制台相关报错追踪发现,出错的位置位于npm包下的dist目录,并且存在内容未定义,初步判定构建错误:
四、解决方案
1. 在依赖中加入@babel/runtime包;
npm install @codesandbox/sandpack-react@latest @babel/runtime
2. 指定入口文件/index.js;
3. 降级@codesandbox/sandpack-react到稳定版本比如2.6.9
npm install @codesandbox/sandpack-react@2.6.9