DEV Community

Cover image for Create a CLI script in your NextJS project
Philippe Bernard
Philippe Bernard

Posted on • Originally published at blog.philippebernard.dev

Create a CLI script in your NextJS project

You put everything you need in your NextJS project: pages, code, tests, stories... Some of these components come out of the box, like pages. You can add the others easily with Jest, Storybook... you name it.

Sometimes you wish you would also have some scripts you can call from the command line. From such a script, you could reuse the app code you already wrote and also take advantage of the app environment. For example, the Prisma schema and database connection.

There are no scripts folder in a NextJS app by default, so let's build it! We are going to use tsx, which will handle everything for us.

From your NextJS app, install tsx:

yarn add -D tsx
Enter fullscreen mode Exit fullscreen mode

Create scripts/my-script.ts:

console.log("Hello, NextJS+CLI");
Enter fullscreen mode Exit fullscreen mode

Alright, this is just another Hello World script. But here you can use import to access your existing NextJS code from src or other directories. Your app environment is available too.

Declare your script in package.json:

...
"scripts": {
  ...
  "my-script": "tsx scripts/my-scripts.ts"
}
Enter fullscreen mode Exit fullscreen mode

Et voilà! Your script is ready to shine:

yarn my-script
Enter fullscreen mode Exit fullscreen mode

That was fairly easy thanks to tsx!

Top comments (0)