How can I execute a TypeScript / TSX file from a Next.js project in the terminal using ts-node?

One of my go-to tools is ts-node for running individual files.

I'm currently attempting to execute files like ts-node ./page/home.tsx, but I'm encountering issues within my Next.js project.

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

When I look at my tsconfig.json file, I've had to make some modifications from the default settings for a Next.js 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"]
}

Keeping module uncommented results in a "Cannot use import statement outside a module" error, while uncommenting jsx leads to a jsx error.

Update

The app works perfectly with all imports.

I'm puzzled as to why Node is struggling to track this import.

To address this, I created a new tsconfig.node.json:

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

When trying to run any file in the project using:

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

I continue to encounter the same type of error.

Answer №1

Regrettably, Next.js relies on webpack for its build process, which means you cannot directly run the code using ts-node. A workaround is to build the file and then execute it using node. I encountered this situation as well. The trick is to place the file within the pages or pages/api directories to trick Next.js into treating it as an executable file. It appears that all dependencies of the pages/api directory are bundled into chunks.

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

Specifically, in my scenario, I am populating a database with default React prop information, which is a unique approach. Since I am importing frontend files for backend use within a script, using ts-node is not an option.

Answer №2

To execute a TypeScript file, simply use the command npx ts-node filename.ts

For TSX files, you will have to utilize NextJS for processing, and remember to import them before use.

> import { Component } from "Component"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to manage a post request in Next.js

Attempting to establish a POST route within my api directory with next.js. After sending the data to the route, I am having difficulty parsing the data in order to properly store it in the database. What would be the most effective approach for managing ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...

Unlock the full potential of working with TaskEither by utilizing its powerful functionality in wrapping an Option with

After exploring various examples of using TaskEither for tasks like making HTTP requests or reading files, I am now attempting to simulate the process of retrieving an item from a database by its ID. The possible outcomes of this operation could be: The i ...

React's componentDidUpdate being triggered before prop change occurs

I am working with the CryptoHistoricGraph component in my app.js file. I have passed this.state.coinPrices as a prop for this element. import React from 'react'; import axios from 'axios'; import CryptoSelect from './components/cry ...

Implement the TypeScript handleChange function for input fields and dropdown menus

Currently, I am in the process of developing a form using TypeScript and Material-UI components. My objective is to create a change handler function that can be utilized for both select and textfield changes. Below are my state and functions: const [re ...

The problem with the "typescript-react-apollo" codegen plugin is that it is declaring block-scope variables more than once in the generated

Recently, I embarked on a new project utilizing NextJS with graphql-codegen to auto-generate my apollo-react types from the API. Unfortunately, it seems to be generating duplicate exported variables right from the start, causing a typescript error and hi ...

How can data be transferred between controllers in Angular 2 without using URL parameters or the $state.go() function?

I've encountered an issue where I need to pass a parameter from one controller to another without it being visible in the URL. I attempted to do so with the following code: this.router.navigate(['/collections/'+this.name], {id: this.id}); ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Tips for inserting a property into an array of objects when it matches the specified ID

As someone new to Angular, I am encountering an issue and would appreciate some help. Here is an array of objects I am working with: signals = [{ 'signalID': '123' },{ 'signalID': '233' },{ 'signalID': &apo ...

The response of the Typescript Subscription function

I'm struggling with retrieving the subscribe array in NG2. Being new to typescript, I find it difficult to understand how to pass variables between functions and constructors. This is what my code currently looks like: export class RosterPage exten ...

NextJs/Express Server Encounters Domain HTTPS Request Error

Yesterday, I successfully deployed my website on a VPS. Everything was working fine on the VPS IP until I installed certbot on my domain. Unfortunately, I encountered the following error: Mixed Content: The page at 'https://mydomain.com/' was loa ...

How can I assign the output of a function to a variable within a class in Angular?

Is there a way for the Army class to automatically update its CP property with the sum of CP values from all Detachments in the Detachment class? In the Army class, the CP property should reflect the total CP value from all Detachments and be accessible t ...

The art of crafting informative error log messages in Protractor using TypeScript

I am currently utilizing Protractor, written in typescript, to conduct tests on a live website. I am seeking guidance on how to generate log messages when a Protractor test fails. Presently, the only feedback received is a simple YES/NO message, as shown b ...

What category does a Fresh of Deno event fall under?

I'm currently working with Deno and fresh. When it comes to events in islands, what is the type for an event like the one below? export function Sample() { return ( <input type="file" onChange={(e) => ...} // What typ ...

Retrieve the file from the REST API without using the window.open method

I'm looking for a method to download files from an API without using window.open(). I want the download process to start immediately upon calling the API. Currently, I am downloading an .xls file generated by a REST API using window.open() API Endpo ...

What could be the reason for TypeScript throwing an error despite having a condition in place?

Having an issue with TypeScript (TS2531) and its non-null type checking. Here's the scenario: if (this.formGroup.get('inseeActivityCode') !== null) { mergedCompanyActivity.inseeActivityCode = this.formGroup.get('inseeActivityCode&ap ...

The world of TypeScript generics and derived data types

I'm looking to streamline the process of calling multiple functions by creating a function that handles this task. These functions all require similar business logic and cleanup operations. function foo(arg: number) { // perform actions using arg ...

Use eslint in conjunction with jsconfig to set up module path aliases in nextjs for absolute path imports using the "@" symbol

Currently, I am working on importing files with custom aliases in accordance with the guidelines provided in the Next.js documentation. My current method involves transitioning from: import Header from '../../../components/Header'; To: import H ...

React Component Div Containing a Hydration Error

Can someone help me resolve the Hydration error related to a nested div issue? I am working on a component that has two main functions - fetching data and mapping it. However, I keep encountering a hydration error and I'm not sure why it's happe ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...