4 Nov, 2023
(Published in 2025)
$ cat *
// @ts-check
import {hi} from './hi.mjs'
/** @type {() => void} **/
export const main = () => {
const app = document.getElementById('app')
if (!app) {
throw new Error('No app element, app cannot load');
}
app.innerText = hi();
}
// @ts-check
/** @type {() => string} **/
export function hi() {
return 'hi'
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<pre>
sudo apt install node-typescript
tsc --allowJs --noEmit --strict *.mjs --watch
python3 -m http.server
</pre>
<div id="app"></div>
<script type = 'module'>
import {main} from "./hello.mjs"
main();
</script>
</body>
</html>
$ ls *
hello.mjs hi.mjs index.html
An alternative approach is:
mkdir project
cd project
npm init -y
npm pkg set type="module" license="UNLICENSED"
npm i --save react react-dom
npm i --save-dev typescript @types/react @types/react-dom
tsc --init --module es6 --strict --jsx react
Then to build in watch mode:
tsc -w
and for a minified build:
esbuild --bundle --outfile=all.js --minify --sourcemap hello.ts
Here's the code:
$ cat index.html hi.ts hello.ts
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<pre>
sudo apt install node-typescript esbuild
mkdir project
cd project
npm init -y
npm pkg set type="module" license="UNLICENSED"
npm i --save react react-dom
npm i --save-dev typescript esbuild @types/react @types/react-dom
tsc --init --module es6 --strict --jsx react
tsc
esbuild --bundle --outfile=all.js --minify --sourcemap hello.tsx
python3 -m http.server
</pre>
<div id="app"></div>
<script type = 'module'>
import {main} from "./hello.js"
main();
</script>
</body>
</html>
export function hi() {
return 'hi'
}
import {hi} from './hi.js'
import * as ReactDOM from 'react-dom';
export const main = () => {
const app = document.getElementById('app')
if (!app) {
throw new Error('No app element, app cannot load');
}
const root = ReactDOM.createRoot(app);
const element = <h1>{hi()}</h1>;
root.render(element);
}
Be the first to comment.
Copyright James Gardner 1996-2020 All Rights Reserved. Admin.