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

Son*_*123 7 typescript next.js ts-node

我有一个 NextJS/Typescript 项目,我想在其中添加一个 CLI 脚本,该脚本应该处理服务器上的一些文件。

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

示例脚本src/cli.ts

console.log("Hello world");
// Process files
Run Code Online (Sandbox Code Playgroud)

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

ts-node src/cli.ts
Run Code Online (Sandbox Code Playgroud)

但我收到此错误消息:

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.
Run Code Online (Sandbox Code Playgroud)

当我添加空的“export {}”语句时,我收到以下错误消息:

(node:15923) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
Run Code Online (Sandbox Code Playgroud)

据我所知,现在不可能将 NextJS 与 ES 模块一起使用。

还有另一种方法可以在 NextJS 项目中运行脚本吗?也许我需要更改 webpack 配置?

我正在使用最新版本:Next 11、Typescript 4.3、Node 14.18、ts-node 10.13,默认为tsconfig.json, package.json

brc*_*-dd 13

改为运行此命令:

npx ts-node --skip-project src/cli.ts
Run Code Online (Sandbox Code Playgroud)

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

--skip-project标志不会解析/加载您的tsconfig.json内容,因此会忽略"isolatedModules": trueNext.js 所需的内容。

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

另一种方法是重写ts-nodetsconfig.json自己的配置,如下所示:

{
  "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
  }
}
Run Code Online (Sandbox Code Playgroud)

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


phi*_*e_b 13

您可以使用TSX来处理 JavaScript 和 TypeScript,它与 NextJS 配合得很好。不需要额外的配置或任何东西。

安装它:

yarn add -D tsx
Run Code Online (Sandbox Code Playgroud)

在以下位置声明您的脚本package.json

...
"scripts": {
  ...
  "my-cli-script": "tsx src/cli.ts"
},
Run Code Online (Sandbox Code Playgroud)

运行:

yarn my-cli-script
Run Code Online (Sandbox Code Playgroud)


小智 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
  }
}
Run Code Online (Sandbox Code Playgroud)

我添加的只是:"module": "CommonJS",