John Fawcett

Author Archives: John Fawcett

Using Webpack to bundle your Workers modules

Using Webpack to bundle your Workers modules

A brief introduction to bundling your Service Worker scripts.

Using Webpack to bundle your Workers modules
Photo by Joyce Romero / Unsplash

// The simplest Service Worker: A passthrough script
addEventListener('fetch', event => {
  event.respondWith(fetch(event.request))
})

The code above is simple and sweet: when a request comes into one of Cloudflare’s data centers, passthrough to the origin server. There is absolutely no need for us to introduce any complex tooling or dependencies. Nevertheless, introduce we will! The problem is, once your script grows even just a little bit, you’ll be tempted to use JavaScript’s fancy new module system. However, in doing so, you’ll have a little bit of trouble uploading your script via our API (we only accept a single JS file).

Throughout this post, we’ll use contrived examples, shaky metaphors, and questionably accurate weather predictions to explain how to bundle your Service Worker with Webpack.

Webpack

Let’s just say Webpack is a module bundler. That is, if you have code in multiple files, and you tie them together like this:

app.js

// Import the CoolSocks class from dresser.js
import { CoolSocks } from './dresser'
import { FancyShoes } from './closet'

Then you can tell webpack to follow all of those Continue reading

Generating Documentation for TypeScript Projects

Documentation for JavaScript projects has traditionally been generated via annotations inserted as code comments. While this gets the job done, it seems far from ideal. In this post, I’ll explore how to use TypeScript to generate documentation from source code alone.

CC BY-SA 2.0 image by David Joyner

TypeScript is JavaScript with optional types. Here’s a simple example:

// Sends some data to some analytics endpoint
function sendAnalyticsJS(data) {  
  if (typeof data.type !== 'string') {
    throw new Error('The `type` property is required')
  }

  navigator.sendBeacon('/beacon', JSON.stringify(data))
}


// Results in run-time error
//    The `type` property is required
sendAnalyticsJS({ foo: 'bar' })  

The JavaScript code will result in a run-time error. This is fine if the developer catches it early, but it would be better if the developer were warned as the bug was introduced. Here’s the same code written using TypeScript:

// Describe the shape of the data parameter
interface IAnalyticsData {  
  // Type is required
  type: string
  // All other fields are fair game
  [propName: string]: string
}


// We don’t particularly need the data.type check here since
// the compiler will stamp out the majority of those cases.
function sendAnalytics(data: IAnalyticsData) {  
  if  Continue reading