react playground
1.0.0
這是一個react在線代碼編輯器,可實時運行react代碼,支持動態引入自定義文件和第三方依賴包,支持ts,tsx,可嵌入項目使用
基礎示例
ahooks示例
ant-design-charts示例
antd示例
1.0版本之前可能會有一些API變動和功能新增,我會盡快修復並穩定,如果興趣的可以關註一下
npm install react-exercise-playground --save
# or
pnpm install react-exercise-playground --save import { Playground } from 'react-exercise-playground'
export const Demo1 = ( ) => {
return < Playground />
}
Playground是頁面組件,使用時對宿主環境有侵入性(會動態加載一些js和css且默認會改變url hash,可以通過配置saveOnUrl={false}屬性取消對url的改變)。
PlaygroundSandbox是對Playground做了沙盒封裝,功能和配置項完全一致,且完全隔離宿主環境的組件。
僅僅是在文檔或者項目中使用的話,推薦使用PlaygroundSandbox組件
引用命令: import {PlaygroundSandbox} from 'react-exercise-playground/PlaygroundSandbox'
PlaygroundSandbox會從CDN下載包,體積僅有10kb+,gzip後2kb+
後續會增加一個完整包,無外網環境下也可使用,體積會大很多
示例代碼:
import { PlaygroundSandbox } from 'react-exercise-playground'
// import {PlaygroundSandbox} from 'react-exercise-playground/PlaygroundSandbox'
export const Demo2 = ( ) => {
const files = {
'App.tsx' : `import {title} from './const'
function App() {
return <h1>this is {title}</h1>
}
export default App
` ,
'const.ts' : {
code : 'export const title = "demo2"' ,
} ,
}
return (
< >
< h1 >作为组件使用: </ h1 >
< PlaygroundSandbox
showHeader = { false }
showCompileOutput = { false }
fileSelectorReadOnly
width = { 700 }
height = { 400 }
files = { files }
border
theme = 'dark'
options = { {
lineNumbers : false ,
} }
/>
< div style = { { height : '60vh' } } > </ div >
< div >滚动到可视范围内才会加载</ div >
< PlaygroundSandbox
showHeader = { false }
showCompileOutput = { false }
fileSelectorReadOnly
width = { 700 }
height = { 400 }
files = { files }
border
theme = 'dark'
options = { {
lineNumbers : false ,
} }
/>
</ >
)
}| Name | Type | Default | Description |
|---|---|---|---|
| width | string丨number丨undefined | 100vw | 寬度 |
| height | string丨number丨undefined | 100vh | 高度 |
| theme | 'dark'丨'light'丨undefined | 'light' | 主題 |
| showHeader | boolean丨undefined | true | 是否顯示頭部 |
| border | boolean丨undefined | false | 是否顯示邊框 |
| showFileSelector | boolean丨undefined | true | 是否顯示文件tab |
| fileSelectorReadOnly | boolean丨undefined | false | 文件tab是否只讀 |
| showCompileOutput | boolean丨undefined | true | 是否顯示編譯後代碼 |
| defaultSizes | number[]丨undefined | [100,100] | 編輯器和預覽區寬度比例 |
| options | { lineNumbers?: boolean;fontSize?: number;tabSize?: number}丨undefined | undefined | 編輯器配置 |
| files | File | Object | 初始化代碼 |
| importMap | { imports: Record<string, string> } | defaultImportMap | 初始化importmap |
| saveOnUrl | boolean | true | 代碼是否存儲到url上 |
| onFilesChange | (hash:string)=>void | undefined | 代碼變更後的回調,回調參數為文件hash值 |
interface File {
[ key : string ] :
| string
| {
code : string
active ?: boolean
hidden ?: boolean
}
}{
"imports" : {
"react" : " https://esm.sh/[email protected] " ,
"react-dom/client" : " https://esm.sh/[email protected] "
}
}對於這個組件的實現原理和過程我寫了一篇文章,感興趣的可以看一看React終於也有playground了:一個能實時運行React代碼的在線編輯器