如何在 web 页面上实时预览 HTML CSS JS 效果

4 天前
 vfs

因为最近在入门 html css javascript , 也会跟着书实践一下,代码都是很小的代码片段, 过后就丢弃了。 但是将来想用类似效果的时候就又忘记了,就想着在已有的 nextjs + react + tailwindcss 技术栈的网站上支持一下这个功能。

看到好多网站都有类似的效果,但是由于本人是个前端小白,所以在这里请教一下各位大神,有没有好的方案,尽可能简单,毕竟它就是用来写一点点代码片段,预览一下效果的“小玩具”。

感谢!

1760 次点击
所在节点    程序员
20 条回复
vfs
4 天前
看到这个网站做的就非常好: https://playcode.io/html5 , 不知道做到这样有多大难度
hausen
4 天前
感觉这种用 cursor 能做
wanf1020
4 天前
最简单的 innerHTML
rimworld
4 天前
iframe 不就可以
radishzz
4 天前
嵌入 codepen ?
molvqingtai
4 天前
要简单,一行代码就可以做到

https://github.com/umpox/TinyEditor
quietDown
4 天前
@molvqingtai 第一件见的这个,有点意思
Plumbiu
4 天前
写过一篇博客: https://blog.plumbiu.top/posts/blog/implement-playground

简单点,下面这行代码就能用

```ts
import React, { createElement } from 'react'
import { transform, Options } from 'sucrase'

type Scope = Record<string, any>

const transfromOptions: Options = {
transforms: ['jsx', 'flow', 'imports'],
}

function evalCode(code: string, scope: Scope) {
const _require = (k: keyof Scope) => {
return scope[k]
}
const scopeKeys = Object.keys(scope)
const scopeValues = scopeKeys.map((key) => scope[key])
const _exports: Record<string, any> = {}
const fn = new Function('exports', 'require', ...scopeKeys, code)
fn(_exports, _require, ...scopeValues)
return _exports.default
}

interface PlaygroundPreviewProps {
code: string
scope?: Scope
}

export function Preview({ code, scope }: PlaygroundPreviewProps) {
const evalScope: Scope = {
react: React,
React: React,
...(scope ?? {}),
}
const mainCode = transform(code, transfromOptions).code
return createElement(evalCode(mainCode, evalScope))
}
```
Plumbiu
4 天前
又看了一眼,单纯 html 可以用 innerHTML ,安全点用 iframe 做。

如果有 css 样式隔离,可以用 iframe 喝 ShadowRoot 。React 的 ShadowRoot 可以用这段代码 https://github.com/Plumbiu/blog/blob/main/src/components/function/Shadow.tsx
importmeta
4 天前
楼上的都不是前端, VS Code 安这个 Live Server 插件就完事.
importmeta
4 天前
@importmeta 我审题错误了... 嵌入 codepen codesanbox 都行
pikko
4 天前
你要的就是漏上的 codepen / codesanbox
xe2vforesu
4 天前
iframe 就能实现,试试我这个
https://www.easydo.top/apps/webNew
gsw945
4 天前
UnluckyNinja
3 天前
尽可能简单那就是 codepen/jsfiddle 嵌入,最简单最省事。
siweipancc
3 天前
娱乐圈……
bapp
3 天前
data:text/html,<body oninput="i.srcdoc=h.value+'<style>'+c.value+'</style><script>'+j.value+'</script>'"><style>textarea,iframe{width:100%;height:50%}body{margin:0}textarea{width:33.33%;font-size:18}</style><textarea placeholder=HTML id=h></textarea><textarea placeholder=CSS id=c></textarea><textarea placeholder=JS id=j></textarea><iframe id=i>
chenzw2
1 天前
@vfs 这种支持 vue 、react 项目结构,package.json 里的依赖也需要去拉取吧,应该需要后端支持的
vfs
1 天前
@chenzw2 啊, 没看懂你说的。。。我当前用的 nextjs ,前后端都有
vfs
1 天前
@Plumbiu 挺喜欢你这个,奈何太菜了, 看了博客也没明白要怎么实现

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://yangjunhui.monster/t/1130743

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX