diff --git a/src/components/Playground/Transform/index.tsx b/src/components/Playground/Transform/index.tsx index 796ee64..c351015 100644 --- a/src/components/Playground/Transform/index.tsx +++ b/src/components/Playground/Transform/index.tsx @@ -6,6 +6,7 @@ import { IFile, ITheme } from '@/components/Playground/shared' import Compiler from '@/components/Playground/compiler' import { cssToJs, jsonToJs } from '@/components/Playground/files' import { MonacoEditorConfig } from '@/components/Playground/CodeEditor/Editor/monacoConfig' +import { addReactImport } from '@/components/Playground/utils.ts' interface OutputProps { file: IFile @@ -23,8 +24,13 @@ const Preview: React.FC = ({ file, theme }) => { }, []) const compile = (code: string, loader: Loader) => { + let _code = code + if (['jsx', 'tsx'].includes(loader)) { + _code = addReactImport(code) + } + compiler.current - ?.transform(code, loader) + ?.transform(_code, loader) .then((value) => { setCompileCode(value.code) }) diff --git a/src/components/Playground/compiler.ts b/src/components/Playground/compiler.ts index e896478..fd97187 100644 --- a/src/components/Playground/compiler.ts +++ b/src/components/Playground/compiler.ts @@ -9,11 +9,17 @@ class Compiler { void esbuild.initialize({ worker: true, wasmURL: wasm }).then(() => { this.init = true }) - } catch (e) {} + } catch (e) { + /* empty */ + } } transform = (code: string, loader: Loader) => new Promise((resolve) => { + if (this.init) { + resolve(true) + return + } const timer = setInterval(() => { if (this.init) { clearInterval(timer) diff --git a/src/components/Playground/utils.ts b/src/components/Playground/utils.ts index 5cfabc2..d1d9968 100644 --- a/src/components/Playground/utils.ts +++ b/src/components/Playground/utils.ts @@ -13,3 +13,10 @@ export const getPlaygroundTheme = (): ITheme => { const isDarkTheme = JSON.parse(localStorage.getItem(STORAGE_DARK_THEME) || 'false') as ITheme return isDarkTheme ? 'vs-dark' : 'light' } + +export const addReactImport = (code: string) => { + if (!/import\s+React/g.test(code)) { + return `import React from 'react';\n${code}` + } + return code +}