typescript - 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
.
解决方案
改为运行:
npx ts-node --skip-project src/cli.ts
参考:https ://github.com/TypeStrong/ts-node#tsconfig
该--skip-project
标志不会解析/加载您的tsconfig.json
,因此忽略"isolatedModules": true
Next.js 所需的。
您还可以为该选项创建一个单独的tsconfig
文件ts-node
并使用该--project [path]
选项。
另一种方法是覆盖ts-node
你tsconfig.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
推荐阅读
- javascript - 如何将此promise对象转换为带有结果的数组
- java - 在 SharedPreferences 中加密和解密 Android 字符串
- python - 如何在 Python 中获得多类分类问题的相邻准确度分数?
- node.js - 如何防止 npm 为软件包安装 demo/sample/example/test 代码?
- python - 如何捕获仅记录的错误?
- python - 如何重复输入命令?
- java - 为什么 Java BitSet 被打包成 6 个字节?
- android - 从 Firestore 中删除文档
- oracle - Oracle Database 19c 示例模式 :: 从 Oracle SQL Developer GUI 导入示例而不是命令行
- javascript - 无法将 Laravel 刀片文件中的道具传递给 Vue 组件