Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Last active February 23, 2021 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumlocke/a96716230d4f2234dbe227105df000b8 to your computer and use it in GitHub Desktop.
Save callumlocke/a96716230d4f2234dbe227105df000b8 to your computer and use it in GitHub Desktop.
How to run TypeScript CLI tasks in a Next.js app

Assuming you've got a Next.js app that's already using TypeScript to render pages/components or handle API routes, but you also want to be able to run ad hoc build tasks written in TypeScript (perhaps pulling in type files used by the app)...

  1. Add these deps: npm install -D @babel/core @babel/node
  2. Make sure your Next app has an explicit .babelrc file:
// Default Next.js .babelrc (it's OK if you also have extra stuff in it)
{
  "presets": ["next/babel"],
  "plugins": []
}

Now you can run .ts files like this:

babel-node -x .ts myTask.ts

(Put that in a package.json script and run it with npm run taskname, or prefix babel-node with ./node_modules/.bin/ to run it directly.)

It is OK for your task to fail type-checking, it will still run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment