对于 Next.js 项目,可以在 tsconfig.json 中使用 "module": "commonjs" 吗?使用 ts-node 在 Next.js Typescript 项目中运行脚本

cbd*_*per 8 typescript next.js ts-node

tsconfig.json这是由 .net 自动生成的默认文件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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我在项目中运行一些脚本,并且我使用ts-node运行它们。

当我尝试运行有一些导入的脚本时,我遇到了各种各样的错误。

例如:

import fs from "fs";
console.log("HERE");
Run Code Online (Sandbox Code Playgroud)

我得到:Unexpected token export

我注意到如果进行以下更改tsconfig.json

"module": "esnext",  // DELETE THIS LINE
"module": "commonjs" // ADD THIS LINE
Run Code Online (Sandbox Code Playgroud)

现在脚本运行良好。

问题

我不想弄乱由 .tsconfig.json自动生成的内容Next.js。可以做出这样的改变吗?我是否破坏了某些东西或冒着破坏某些东西的风险?我应该创建一个不同的tsconfig.json文件吗?这里最好的选择是什么?

小智 9

将此ts-node字段添加到我的 tsconfig.json 中有效!

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

Run Code Online (Sandbox Code Playgroud)


cbd*_*per 6

我最终选择不弄乱Next.js文件的默认设置tsconfig.json

所以我创建了一个新的配置文件,并将其命名为tsconfig_scripts.json.

并且内容基本相同tsconfig.json。我刚刚更新了这些部分:

tsconfig_scripts.json

"module": "commonjs",      // CHANGED TO THIS
"ts-node": {               // ADDED THIS
  "files": true
},
Run Code Online (Sandbox Code Playgroud)

我还添加了一个 npm 脚本以ts-node更简单的方式调用:

包.json

"scripts": {
  "ts-node-script": "ts-node --project tsconfig_scripts.json -r tsconfig-paths/register"
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • --project tsconfig_scripts.json设置新的自定义配置文件
  • -r tsconfig-paths/register允许您在脚本文件上使用路径别名

要使用它,您只需从 CLI 运行:

npm run ts-node-script path/to/your/script.ts
Run Code Online (Sandbox Code Playgroud)