Deno and ES6 Modules

Continuing my expedition into the JavaScript front-end land…I like Deno. A lot. It does lots of things right (from my point of view, e.g. permissions), and it fixes many problem Node.js has. Using Deno for back-end work is straightforward, but since I focus currently on the front-end side, how can I create front-end JavaScript with Deno and still use Deno’s testing framework?

It’s actually not hard. Here a small TypeScript file:

import capitalize from "https://unpkg.com/lodash-es@4.17.15/capitalize.js";

function main() {
  console.log(capitalize("hello from the web browser"));
}

function sum(a: number, b: number): number {
    return a+b;
}

window.onload = () => {
  console.info(capitalize("module loaded!"));
};

export { main, sum }                                                                                                   

embedded in a simple index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>Testing Deno</title>
</head>
<body>
    <div>Some Text</div>
<script type="module">
    import {main, sum} from './dist/browser.js';
    main();
    console.log(sum(5,6));
    console.log("Done.");
</script>
</body>
</html>

So far that’s straightforward: loading index.html runs main() and prints out the sum of 5+6 on the console.

Here the test script:

import { assertEquals } from "https://deno.land/std@0.106.0/testing/asserts.ts";

import { sum } from "./example.ts";

Deno.test("Sum 5 and 7", () => {
  assertEquals(sum(5, 7), 12);
});

Again, standard Deno. And deno test works as expected. And to deploy as plain-JavaScript, a simple deno bundle src/example.ts dist/browser.js does the trick.

And there you go: plain TypeScript and yet the logic can be tested with the normal deno test command. No extra tools needed. No Babel, WebPack, tsc. No require vs import either.

deno_dom is not yet working enough though (see the stub definition of addEventListener() here), so until then only basic DOM operations work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create your website with WordPress.com
Get started
%d bloggers like this: