8

This is the default tsconfig.json file that was generated automatically by Next.js.

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",            // <=== THIS IS THE PROBLEM
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

My problem with it is that I run some scripts across my project, and I use ts-node to run them.

I was getting all sorts of errors when trying to run scripts that had some imports on them.

For example:

import fs from "fs";
console.log("HERE");

I was getting: Unexpected token export

And I noticed that if make the following change to tsconfig.json

"module": "esnext",  // DELETE THIS LINE
"module": "commonjs" // ADD THIS LINE

Now the script runs fine.

QUESTION

I don't want to mess with the tsconfig.json that was auto generated by Next.js. Is it ok to make that change? Am I breaking or risking to break something? Should I create a different tsconfig.json file? What is the best option here?

Toto
  • 89,455
  • 62
  • 89
  • 125
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

2 Answers2

9

Adding this ts-node field to my tsconfig.json worked!

{
  "compilerOptions": {
    ...
  },
  "include": [...],
  "exclude": ["node_modules"],
  "ts-node": {
    "transpileOnly": true,
    "compilerOptions": {
      "module": "commonjs"
    }
  }
}

Alex Akagi
  • 91
  • 1
  • 2
6

I ended up choosing not to mess with Next.js default settings for the tsconfig.json file.

So I created a new config file that I've named tsconfig_scripts.json.

And it has basically the same content of tsconfig.json. I've just updated these parts:

tsconfig_scripts.json

"module": "commonjs",      // CHANGED TO THIS
"ts-node": {               // ADDED THIS
  "files": true
},

I've also added an npm script to call ts-node in an easier manner:

package.json

"scripts": {
  "ts-node-script": "ts-node --project tsconfig_scripts.json -r tsconfig-paths/register"
}

Notes:

  • --project tsconfig_scripts.json sets the new custom config file
  • -r tsconfig-paths/register allows you to use path aliases on script files

To use it, you just run this from the CLI:

npm run ts-node-script path/to/your/script.ts
cbdeveloper
  • 27,898
  • 37
  • 155
  • 336