Created
December 17, 2020 18:03
-
-
Save yysun/8cdf03e8399362ecec056218d4c74709 to your computer and use it in GitHub Desktop.
Compile TypeScript in the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://unpkg.com/typescript@latest/lib/typescriptServices.js"></script> | |
<script src="https://unpkg.com/apprun"></script> | |
<script src="my-tsc.js" defer></script> | |
</head> | |
<body> | |
<script type="text/typescript"> | |
class Xkcd extends Component { | |
state = async () => { | |
const response = await fetch('https://xkcd-imgs.herokuapp.com/'); | |
const comic = await response.json(); | |
return comic; | |
}; | |
view = comic => <img src={ comic.url } />; | |
} | |
app.render(document.body, <Xkcd />); | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.addEventListener('DOMContentLoaded', (event) => { | |
const compilerOptions = { | |
"target": "es2015", | |
"jsx": "react", | |
"jsxFactory": "app.h", | |
"jsxFragmentFactory": "app.Fragment", | |
"lib": ["dom", "es2015", "es5"], | |
"experimentalDecorators": true, | |
"skipLibCheck": true | |
}; | |
const scripts = document.getElementsByTagName("script"); | |
window.ts && [...scripts].forEach(script => { | |
if(script.attributes['type'] && | |
script.attributes['type'].value.includes("text/typescript")) { | |
const tsCode = window.ts.transpile(script.innerText, compilerOptions); | |
const new_script = document.createElement('script'); | |
new_script.attributes['type'] = script.attributes['type'].value.replace("text/typescript", ""); | |
new_script.innerText = tsCode; | |
script.replaceWith(new_script); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment