首页 > 解决方案 > NextJS:在服务器上运行 Typescript 脚本

问题描述

我有一个 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.

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

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

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

标签: typescriptnext.jsts-node

解决方案


改为运行:

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

参考: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
  }
}

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


推荐阅读