Error with top-level await while running data migration script

1 replies
Last updated: May 26, 2023
Hello! I am trying to write some data migration scripts and started with something basic and am running into an error that, while it is not really a Sanity issue, it is while I’m running through
sanity exec
and was not sure if that had anything to do with it. I’m running my command as such from the root of my Sanity project
sanity exec ./scripts/migration/migrateBlips.ts --with-user-token
and my code which is pretty straight forward gives me the error
Top-level await is currently not supported with the "cjs" output format
Here is my code

import { getCliClient } from 'sanity/cli';


const client = getCliClient().withConfig({ apiVersion: '2023-05-24' })

const loadCategories = async () => {
    const categories = await client.fetch('*[_type == "category"]');
    categories.forEach(category => {
        console.log(category)
    });
}

try {
  await loadCategories();
} catch (error) {
  console.error(error);
}
Thanks for any pointers…..
May 26, 2023, 5:15 PM
Looks like wrapping in an IIFE helps

(async () => {
  await loadCategories();
})();
May 26, 2023, 5:29 PM

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?