Skip to content

Working with client side TypeScript

Marwane Kalam-Alami edited this page Jul 21, 2020 · 5 revisions

Most of the action happens server-side, so the site is fairly light on client-side TypeScript. Try to make things work without JS where it doesn't harm the user experience too much. This is preferred for keeping the code simple and fast to develop/maintain, but also for accessibility, performance and SEO.

Browser support

We aim to support all ES5-compliant browsers (IE9 and up), see caniuse.com. Babel is used to compile modern TypeScript (see the env preset) into ES5, and core-js provides features missing from old browsers.

Webpack is used to bundle all custom scripts (as opposed to third-party scripts) into a standalone file. The entry point is /assets/js/site.ts.

Component system

The general strategy of triggering JavaScript enhancements in a page is through classes (prefixed with js-), using data- attributes to pass additional parameters if necessary. For example, if you wanted to create a TypeScript component foo, you'd invoke it as follows:

  <div class="js-foo" data-js-foo-param="{{ getFooParam }}"></div>

Then write your script, as a module that exports a single function:

export default function foo () {
  $('.js-foo').each(function () {
    const param = $(this).attr('data-js-foo-param')
    ...
  })
}

Finally, register it to site.ts:

import foo from "./bar/foo";

foo();

Avoid inline <script> elements as much as possible. These scripts can't be processed by Babel, which makes them inefficient, hard to maintain, and prone to breakage.