【问题标题】:How do I run a a typescript / tsx file from nextjs project in terminal using ts-node?如何使用 ts-node 在终端中从 nextjs 项目运行 typescript / tsx 文件?
【发布时间】:2022-01-31 02:51:12
【问题描述】:

我经常喜欢使用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 错误

更新

该应用程序完全可以使用所有导入功能。

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

我已经添加了一个新的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

我遇到了同样的错误。

【问题讨论】:

  • createWidget 是从哪里来的?
  • 我有一个导出文件“/components/widget/Widget.tsx”
  • 使用ts-node 运行 React 组件文件的用例是什么?
  • @juliomalves 我想测试文件和 console.log 一个变量

标签: typescript next.js


【解决方案1】:

不幸的是,nextjs 使用 webpack 构建,因此您无法使用 ts-node 执行代码。执行文件的一种方法是构建它,然后使用 node.js 运行它。这适用于我的情况。这里的问题是文件需要在pagespages/api 内,这将“愚弄”下一步构建可执行文件。 pages/api 的所有依赖项似乎都捆绑成块。

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

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

【讨论】:

    【解决方案2】:

    您可以使用npx ts-node filename.ts 运行任何打字稿文件

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

    > import { Component } from "Component"
    

    【讨论】:

    • 我已经在导入依赖项并且前端应用程序工作正常。问题是节点无法正确识别我的文件中的导出。这个评论是有问题的,因为你不能为打字稿包含 .tsx 扩展名。您收到错误:导入路径不能以“.tsx”扩展名结尾
    猜你喜欢
    • 2023-01-10
    • 2021-02-25
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多