Skip to content

Commit

Permalink
feat: fetch后端code runner MVP
Browse files Browse the repository at this point in the history
  • Loading branch information
1360151219 committed Oct 18, 2023
1 parent b64ef22 commit a0eaa0c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
<body>
<script type="importmap"></script>
<div id="root"></div>
<code id="__CODE_RUN__" style="color: rgb(249, 146, 146)"></code>
</body>
<script>
window.addEventListener('message', (e) => {
const { type, data } = e.data;
// 编译
if (type === 0) {
const { code, importMap } = data;
const { code, importMap, runcode = '' } = data;
// Import Map
if (importMap.size > 0) {
const ImportMapScript = document.querySelector(
Expand All @@ -37,8 +38,13 @@
const compileScript = document.createElement('script');
compileScript.id = CompileScriptId;
compileScript.type = 'module';
compileScript.innerHTML = code;
compileScript.innerHTML = `try{${code}}catch(err){console.log(err)}`;
document.body.appendChild(compileScript);

document.getElementById('__CODE_RUN__').innerHTML = runcode.replace(
/[\n]/g,
'<br />'
);
}
});
</script>
Expand Down
24 changes: 22 additions & 2 deletions packages/design/components/MonacoEditor/workers/compilerWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ import { getInternalModule, getModulesEntry } from '../utils';

const ModuleDependencyGraph = new Map<'entry' | 'dependencies', any>();

const fetchCodeRunner = async (code: string) => {
try {
const response = await fetch(`http://localhost:3000?code=${code}`, {
method: 'GET',
});
return await response.text();
} catch (error) {
return error.toString();
}
};
const babelTransform = (filename: string, code: string, modules: Module[]) => {
// 目前只存在一个入口
if (
Expand Down Expand Up @@ -119,7 +129,7 @@ const babelTransform = (filename: string, code: string, modules: Module[]) => {
}
};

self.addEventListener('message', (e) => {
self.addEventListener('message', async (e) => {
const { type, data } = e.data;

if (type === MessageChangeType.Compile) {
Expand All @@ -138,10 +148,20 @@ self.addEventListener('message', (e) => {
) {
return;
}

const babelTransformResult = babelTransform(
String(entryModule.key),
entryModule.value,
modules
);
const codeRunnerResult = await fetchCodeRunner(babelTransformResult?.code);
// 发送结果回主线程
self.postMessage({
type,
data: babelTransform(String(entryModule.key), entryModule.value, modules),
data: {
...babelTransformResult,
runcode: codeRunnerResult,
},
});
}
});

0 comments on commit a0eaa0c

Please sign in to comment.