'How do I run a a typescript / tsx file from nextjs project in terminal using ts-node?

I frequently like to use ts-node to execute a single file.

I'm looking to be able to run anything like ts-node ./page/home.tsx.

I'm having issues doing so within my nextjs project.

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

My tsconfig.json looks like this, having to swap out the commented ones that are the default for a nextjs project.

{
  "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"]
}

Without module commented I get Cannot use import statement outside a module Without jsx commented I get a jsx error

Update

The app fully functions with all imports.

I'm not sure I understand why node is not able to track this import.

I've since added a new tsconfig.node.json

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

and I try to execute any file in my project:

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

I get the same kind of error.



Solution 1:[1]

Unfortunately nextjs uses webpack to build and so you can't execute the code with ts-node. One way to execute a file is to build it then run it with node. This worked for my case. The issue here is that the file needs to be within pages or pages/api this will 'fool' next into building an executable file. All dependencies of pages/api seem to be bundled into chunks.

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

In my specific case, I am seeding a database with default react prop information, a fringe idea. Because I am importing front-end files to use the on the backend, in a script, I can't use ts-node.

Solution 2:[2]

You can run any typescript file with npx ts-node filename.ts

TSX files need to be processed by NextJS so to use them they need to be imported.

> import { Component } from "Component"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ThomasReggi
Solution 2