NextJS:在服务器上运行 Typescript 脚本 [英] NextJS: Run a Typescript script on the server
问题描述
我有一个 NextJS/Typescript 项目,我想在其中添加一个 CLI 脚本,该脚本应该处理服务器上的一些文件.
I have a NextJS/Typescript project where I want to add a CLI script which should process some files on the server.
很遗憾,我无法运行脚本.
Unfortunately I don't manage to run the script.
示例脚本src/cli.ts
:
console.log("Hello world");
// Process files
我尝试使用以下命令运行脚本:
I tried to run the script with:
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 {}"语句时,我收到以下错误消息:
When I add an empty 'export {}' statement I get this error message:
(node:15923) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
据我所知,现在无法将 NextJS 与 ES 模块一起使用.
As far as I know it is now not possible to use NextJS with ES modules.
还有其他方法可以在 NextJS 项目中运行脚本吗?也许我需要更改 webpack 配置?
Is there another way to run the script in a NextJS project? Maybe I need to change the webpack config?
我使用的是最新版本:Next 11、Typescript 4.3、Node 14.18、ts-node 10.13,默认为 tsconfig.json
、package.json
.
I'm using the latest versions: Next 11, Typescript 4.3, Node 14.18, ts-node 10.13 with the default 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 需要.
The --skip-project
flag will not resolve/load your tsconfig.json
and, thus, ignore the "isolatedModules": true
required by Next.js.
您还可以为 ts-node
创建一个单独的 tsconfig
文件并使用 --project [path]
选项.
You can also create a separate tsconfig
file for ts-node
and use the --project [path]
option.
另一种方法是在 tsconfig.json
本身中覆盖 ts-node
的配置,如下所示:
Another way is to override configuration for ts-node
in your tsconfig.json
itself like this:
{
"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-推荐
这篇关于NextJS:在服务器上运行 Typescript 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!