NextJS:在服务器上运行 TypeScript 脚本

7

我有一个使用NextJS/Typescript开发的项目,想要添加一个CLI脚本,在服务器上处理一些文件。

不幸的是,我无法运行该脚本。

示例脚本src/cli.ts

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

我尝试使用以下命令运行脚本:

ts-node src/cli.ts

但是我收到了这个错误消息:

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.

当我添加一个空的 'export {}' 语句时,我会得到以下错误信息:
(node:15923) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

据我所知,目前无法在ES模块中使用NextJS。在NextJS项目中运行脚本的另一种方式是否存在?也许需要更改webpack配置?我正在使用最新版本:Next 11、Typescript 4.3、Node 14.18、ts-node 10.13和默认的 tsconfig.json 和 package.json。请注意保留HTML标记。
3个回答

13

请运行以下内容:

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

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

--skip-project 标志将不会解析/加载您的 tsconfig.json 文件,因此忽略 Next.js 所需的 "isolatedModules": true

您还可以为 ts-node 创建单独的 tsconfig 文件,并使用 --project [path] 选项。

另一种方式是在 tsconfig.json 中重写 ts-node 的配置,如下所示:

{
  "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.

      "isolatedModules": false
    }
  },

  "compilerOptions": {
    // typescript options here
  }
}

参考: https://github.com/TypeStrong/ts-node#via-tsconfigjson-recommended


10
您可以使用TSX,它能够很好地与NextJS配合使用,支持JavaScript和TypeScript。无需额外的配置或其他任何东西。
安装它:
yarn add -D tsx

package.json 中声明你的脚本:
...
"scripts": {
  ...
  "my-cli-script": "tsx src/cli.ts"
},

运行它:
yarn my-cli-script

1
我简直要疯了。尝试了大约20种不同的解决方案,直到这个方法起作用。谢谢!!! - Marek Lisý
@MarekLisý 我也是 :) - philippe_b
1
谢谢!这对我有用。如果你愿意,你也可以只用 npx tsx path/to/your/script.ts,而不需要将 tsx 添加到依赖项中,并在 package.json 中添加一个适当的脚本。 - undefined

1

继续 @brc-dd 的回答。

--skip-project 标志现在是 --skipProject

对于新的 TSConfig,在运行脚本时指定,您需要以下内容:

{
  "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
  }
}

我所添加的是:"module": "CommonJS"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接