Nail Web Workers with Typescript

Dan Merlea
2 min readMay 16, 2020

I was working these days on my game https://neoinvade.com and I’ve faced some serious issues with the amazing single threaded javascript. If you don’t know what single thread means, the easiest explanation would be that even though you can async some of the commands which give you the fake impression of a parallel run, there is only one call-stack so the UI will still get laggy from large data processing on CPU.

So how do you do a legit parallel run of a CPU heavy code? Using a Web Worker!

I’ve had a hard time configuring typescript and web workers, so I’ve decided to put this info together and help some people out there.

Firstly you need a bundler. I’ve spent hours trying to configure watchify & browserify, but without any luck. If you’re going through the same issue, I’ve found webpack much more advanced and easier to use and configure.

{
mode: 'development',
devtool: 'source-map', // used to show ts files in debugger &
better error stack
entry: {
bundle: '<main-app-entry>.ts', // replace it with real files
worker: '<worker-path>.ts' // replace it with real files
},
output: {
filename: '[name].js', // [name] is an actuall variable
path: path.resolve(__dirname, 'assets/js'),
},
watch: true, // allows watching instead of one-time build
watchOptions: {
aggregateTimeout: 200,
poll: 1000
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
module: {
rules: [{…

--

--