如何在终端中使用ts节点从nextjs项目运行typescript/tsx文件



我经常喜欢使用ts-node来执行单个文件。

我希望能够运行任何类似ts-node ./page/home.tsx的程序。

我在nextjs项目中遇到了这样做的问题。

export const WidgetList = createWidget<ButtonListProps>(WidgetListProps)
^
TypeError: (0 , Widget_1.createWidget) is not a function

我的tsconfig.json看起来是这样的,必须替换掉注释的那些,它们是nextjs项目的默认值。

{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
// "module": "esnext",
"module": "CommonJS",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
// "jsx": "preserve",
"jsx": "react",
"incremental": true,
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}

没有module评论,我得到了Cannot use import statement outside a module没有jsx评论我得到一个jsx错误

更新

该应用程序在所有导入中都能正常工作

我不确定我是否理解为什么节点无法跟踪此导入。

我添加了一个新的tsconfig.node.json

{
"compilerOptions": {
"strictNullChecks": true,
"module": "NodeNext",
"jsx": "react",
"esModuleInterop": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
}

我尝试执行我的项目中的任何文件:

ts-node --project ./tsconfig.node.json ./components/widget/Widget.tsx

我也犯了同样的错误。

不幸的是,nextjs使用webpack进行构建,因此无法使用ts-node执行代码。执行文件的一种方法是先构建文件,然后用node运行它。这对我的案子有效。这里的问题是,文件需要在pagespages/api中,这将"欺骗"下一步构建可执行文件。pages/api的所有依赖项似乎都被捆绑成块。

yarn next build    
node ./.next/server/pages/api/initialize.js

在我的具体案例中,我正在为一个数据库播种默认的反应道具信息,这是一个边缘想法。因为我正在导入前端文件以在后端使用,所以在脚本中,我不能使用ts-node

您可以使用npx ts-node filename.ts运行任何类型的脚本文件

TSX文件需要由NextJS处理,因此要使用它们,需要导入它们。

> import { Component } from "Component"

最新更新