Create a CLI script in your NextJS project
Reuse your NextJS app code in a script you can call from the command line
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
Create scripts/my-script.ts
:
console.log("Hello, NextJS+CLI");
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"
}
Et voilà! Your script is ready to shine:
yarn my-script
That was fairly easy thanks to tsx!