Sep 13 '22 ~ 3 ~ 2 mins

Write Typescript in the browser with SystemJs

(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' }
        },

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>

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>
// Attach external event handlers to window so they can be called from index.html
(<any>window).onBtExcludeMedalColumns = onBtExcludeMedalColumns;

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 :) )


Headshot of Stephen Cooper

Hi, I'm Stephen. I'm a senior software engineer at AG Grid. If you like my content then please follow / contact me on 🦋 Bluesky or 𝕏 (X) and say hello!