Search code examples
typescriptnext.jsts-node

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.


Solution

  • Following on from @brc-dd answer.

    The --skip-project flag is now --skipProject

    And for the new TSConfig to specify when running the script you would need the following:

    {
      "extends": "ts-node/next/tsconfig.json",
    
      "ts-node": {
        "compilerOptions": {
          // compilerOptions specified here will override those declared below,
          // but *only* in ts-node.  Useful if you want ts-node and tsc to use
          // different options with a single tsconfig.json.
    
          "module": "CommonJS",
          "isolatedModules": false
        }
      },
    
      "compilerOptions": {
        // typescript options here
      }
    }
    

    All I added to this was: "module": "CommonJS",