Published on

Fix for Module format "cjs" does not support top-level await

Authors

Recently, I was working on my side project and deployed the background function to Defer.run

And I was greeted with the following error message 😭

What's the cause of it?

Apparently, the platform that I'm using does not support top-level await and one of my package dependencies is using it.

And that resulted in build failure.

What's the fix?

  1. See if you can enable it in your environment.
  2. If possible, rewrite the code and migrate it from top-level await.

In my case, I went with the 2nd option.

Example Snippets

Top-level await

// Based on  https://github.com/sindresorhus/temp-dir/blob/main/index.js
import fs from 'node:fs';
import os from 'node:os';

const temporaryDirectory = await fs.promises.realpath(os.tmpdir());

Without Top-level await

import fs from 'node:fs';
import os from 'node:os';
const temporaryDirectory = fs.realpathSync(os.tmpdir());

Happy fixing issues!