[英]How do I run a a typescript / tsx file from nextjs project in terminal using ts-node?
我经常喜欢使用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
我得到同样的错误。
您可以使用 npx npx ts-node filename.ts
运行任何 typescript 文件
TSX 文件需要由 NextJS 处理,因此需要导入它们才能使用它们。
> import Component form "Component.tsx"
不幸的是 nextjs 使用 webpack 来构建,所以你不能用ts-node
执行代码。 执行文件的一种方法是构建它,然后使用 node.js 运行它。 这适用于我的情况。 这里的问题是该文件需要在pages
或pages/api
中,这将“愚弄”下一步构建可执行文件。 pages/api 的所有依赖项似乎都捆绑成块。
yarn next build
node ./.next/server/pages/api/initialize.js
在我的具体情况下,我正在使用默认反应道具信息播种数据库,这是一个边缘想法。 因为我正在导入前端文件以在后端使用 ,所以在脚本中,我不能使用ts-node
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.