繁体   English   中英

如何使用 ts-node 在终端的 nextjs 项目中运行 typescript / tsx 文件?

[英]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 运行它。 这适用于我的情况。 这里的问题是该文件需要在pagespages/api中,这将“愚弄”下一步构建可执行文件。 pages/api 的所有依赖项似乎都捆绑成块。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM