Home > other >  NextJS: Run a Typescript script on the server
NextJS: Run a Typescript script on the server

Time:10-15

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.

CodePudding user response:

Run this instead:

npx ts-node --skip-project src/cli.ts

Reference: https://github.com/TypeStrong/ts-node#tsconfig

The --skip-project flag will not resolve/load your tsconfig.json and, thus, ignore the "isolatedModules": true required by Next.js.

You can also create a separate tsconfig file for ts-node and use the --project [path] option.

  • Related