Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS: Run a Typescript script on the server

I have a NextJS/Typescript project where I want to add a CLI script which should process some files on the server.

Unfortunately I don't manage to run the script.

Example script src/cli.ts:

console.log("Hello world");
// Process files

I tried to run the script with:

ts-node src/cli.ts

But I get this error message:

src/cli.ts:1:1 - error TS1208: 'cli.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.

When I add an empty 'export {}' statement I get this error message:

(node:15923) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

As far as I know it is now not possible to use NextJS with ES modules.

Is there another way to run the script in a NextJS project? Maybe I need to change the webpack config?

I'm using the latest versions: Next 11, Typescript 4.3, Node 14.18, ts-node 10.13 with the default tsconfig.json, package.json.

like image 699
Sonson123 Avatar asked Apr 13 '26 16:04

Sonson123


1 Answers

You can use TSX, which plays nicely with NextJS, for both JavaScript and TypeScript. No need for extra configuration or anything.

Install it:

yarn add -D tsx

Declare your script in package.json:

...
"scripts": {
  ...
  "my-cli-script": "tsx src/cli.ts"
},

Run it:

yarn my-cli-script
like image 139
philippe_b Avatar answered Apr 15 '26 12:04

philippe_b