本文使用开源的 monaco-editor( https://github.com/Microsoft/monaco-editor ) 编辑工具来实现一个在线的 code 工具. 在线预览 http://code.yardwill.com/ , 因为懒得上 cdn, 所以目前访问速度可能有点慢.
image.PNG
1. monaco-editor
左边一块就是我们的 editor, 在这里我们可以实时编辑 code. 并且具有代码提示.
image.PNG
2. console 结果
右边一块是我们的 console 结果. 我们可以来测试一下. 输入代码之后点击运行.
image.PNG
当然也会对错误进行处理.
image.PNG
可以通过清除日志来删除所有的 console 内容.
3. 原理
原理也很简单, 获取 editor 里的 text, 然后通过 eval 在浏览器端执行代码, 最后覆盖浏览器内的 console 方法, 来达到 console 内容的获取.
4. 源码
https://github.com/YardWill/live-code
来源: http://www.jianshu.com/p/e978ebab4b87