Write Typescript in the browser with SystemJs

Stephen Cooper - Sep 13 '22 - - Dev Community

(This post is just a rough public note about a side effect of some of my work. May or may not be helpful :) )

Do you love Typescript and wish you could use it to power a simple toy HTML sites that you want to play with? Well you can with SystemJs and a bit of on the fly browser compilation.

You don't always need a fancy setup :P

Demo Index.html + Typescript files

Check out this demo on Plunker that shows you how you can write Typescript files and use their methods from your Index.html file.

Yes, this does require you to get your SystemJs config setup right but that is why I am sharing this starter that I used for our AG Grid demos so that you can get started easily.

System.config({
        // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
        transpiler: "ts",
        typescriptOptions: {
            // Copy of compiler options in standard tsconfig.json
            target: "es5",
            module: "system", //gets rid of console warning
            moduleResolution: "node",
            sourceMap: false,
            emitDecoratorMetadata: true,
            experimentalDecorators: true,
            lib: ["es2015", "dom"],
            noImplicitAny: true,
            suppressImplicitAnyIndexErrors: true
        },
        meta: {
            typescript: {
                exports: "ts"
            },
            '*.css': { loader: 'css' }
        },
Enter fullscreen mode Exit fullscreen mode

Aside from the systemjs.config.js file the main part of the code are as follows:

<script src="https://unpkg.com/systemjs@0.19.47/dist/system.js">        </script>
<script src="systemjs.config.js"></script>
<script>
  System.import('./main.ts')
        .catch(function(err) { console.error(err); });
</script>

Enter fullscreen mode Exit fullscreen mode

Attaching methods to the window scope so can be called from HTML. (This is done for you when you just use a plain Javascript file)

<button onclick="onBtExcludeMedalColumns()">Exclude Medal Columns</button>
Enter fullscreen mode Exit fullscreen mode
// Attach external event handlers to window so they can be called from index.html
(<any>window).onBtExcludeMedalColumns = onBtExcludeMedalColumns;
Enter fullscreen mode Exit fullscreen mode

That's kind of it!

(This post is just a rough public note about a side effect of some of my work. May or may not be helpful :) )

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .