Encountering an error with the ".ts" file extension when attempting to execute a ts-node script

I am currently facing an issue while trying to execute a script that consists of two .ts files in a regular folder. One file contains the script, and the other has helper functions required to run it. Additionally, I am importing external libraries such as axios and form-data.

However, when I attempt to run the script using ts-node: node script.ts, an error message is displayed:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

Here is a snippet of my package.json:

{
  "dependencies": {
    "@types/node": "^17.0.23",
    "axios": "^0.26.1",
    "form-data": "^4.0.0",
    "showdown": "^2.0.3",
    "ts-node": "^10.7.0",
    "typescript": "^4.6.3"
  },
  "type": "module"
}

Furthermore, my tsconfig.json configuration is as follows:

{
  "compilerOptions": {
    "esModuleInterop": true
  },
  "include": ["/**/*.ts"],
  "exclude": ["node_modules"]
}

The import statements in the script.ts file are:

import { datoManagementPrimaryEnvironment } from "./content.management";
import {
  createContent,
  uploadToCloudfare,
  getEntryFromDatoWithTheId,
  getFilters,
} from "./helpers";

and in helpers.ts:

import { datoManagementPrimaryEnvironment } from "./content.management";
import axios from "axios";
import FormData from "form-data";
var showdown = require("showdown");

If anyone has any insights on what might be causing this issue, I would greatly appreciate your help. Thank you!

Answer №1

Make sure to include the --esm flag in your ts-node command.

For example:

ts-node --esm index.ts

To use this flag, you need to update your module setting to a newer version (such as nodenext or node16) and ensure that module resolution is also set to a newer method in your tsconfig file.

Answer №2

This approach proved to be effective for me. Kudos to @Slava for guiding me in the right direction.

Directing to the documentation here.

The simplest way is to include esm: true in your TypeScript configuration file:

{   
  "$schema": "https://json.schemastore.org/tsconfig",  
  "extends": "@tsconfig/node-lts-strictest-esm/tsconfig.json",  
  "compilerOptions": {
    // …   
  },   
  "include": [
    // …   
  ],   
  "ts-node": {
    "esm": true, // «———— enabling ESM for ts-node   
  }, 
} 

The only thing I overlooked was including "esm": true, since I already had the ts-config set up for esm. However, if starting from scratch, it's advisable to also add the "$schema" and "extends".

In addition, I found it necessary to insert

"type": "module"
in the package.json file.

Answer №3

Erase the line

"type": "module"
in your package.json

Update your tsconfig.json with the following:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "moduleResolution": "node"
  },
  "include": ["/**/*.ts"],
  "exclude": ["node_modules"]
}

Answer №4

Using TypeScript with Native ESM: A Step-by-Step Guide

  1. Start by updating your package.json with the following configuration:
{
  "type": "module",
  // …
}
  1. Next, install the @tsconfig/node-lts-strictest-esm dependency by running:
npm i -D @tsconfig/node-lts-strictest-esm
  1. Update your tsconfig.json to include:
{
  "$schema": "https://json.schemastore.org/tsconfig",
  "extends": "@tsconfig/node-lts-strictest-esm/tsconfig.json",
  // …
}
  1. When importing modules in your TypeScript files, remember to use the .js extension. For example:
import { Foo } from './common/foo.js';
  1. Instead of using ts-node file.ts, use ts-node-esm file.ts to run your TypeScript files.

Following these steps should help you seamlessly use TypeScript with native ESM.


For a more comprehensive guide, refer to this detailed resource.

Answer №5

This one-line solution has changed everything for me:

ts-node --compiler-options '{\"module\": \"commonjs\"}' /path/to/file.ts

Answer №6

If you're looking to utilize ts-node, consider executing the file using ts-node scripts.ts rather than node scripts.ts.

For further guidance, check out the usage examples available on npmjs.com

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

Is it possible for me to automatically send the user's email and username through code without requiring any information from them while using the tawk.to chat widget?

I need assistance with automatically sending the user's email and name when they open a chat window. I have tried various methods to pre-fill the form data but it still appears empty. Please let me know if there is something I am missing. Thank you ta ...

What is the purpose of the `Bitwise operator |` in the `d3.shuffle` source code and how can it be understood

Learning about the Bitwise operator | can be found in the document here and a helpful video tutorial here. However, understanding the purpose and significance of | may not come easily through basic examples in those resources. In my exploration of the sou ...

How would you go about creating a VueJS component that displays a table with a set number of columns and automatically distributes the cells within them?

Hey there! I'm currently working with a VueJS component that looks like this: <template> <div> <table> <tbody> <tr v-for="(item, index) in items" :key="index"> <t ...

Next.js encountered an issue with the element type, as it expected either a string for built-in components or a class/function for composite components, but received undefined instead

Recently, while working with next js, I encountered an issue when trying to import a rich text editor into my project. Specifically, when attempting to integrate react-draft-wysiwyg, an error message was displayed: Error: Element type is invalid... (full e ...

Utilizing jQuery and CSS to make an entire div clickable, and activate an 'a' tag hover state upon hovering

Looking to create a clickable link for the .wrapper div that directs users to the location of a.icon. Want the .wrapper div to activate the a.icon:hover state when hovered over, not just when hovering over the icon itself. Any assistance would be highly a ...

Bootstrap wysiwyg5 editor validation: Ensuring accuracy in your content creation

Currently, I have integrated the Bootstrap wysiwyg5 editor into a form. One of the fields in this form, specifically the text area, is mandatory and cannot be left empty. I am facing a challenge in validating whether the user has entered any content into t ...

What is the process for delivering a promise?

In the context of my Angular application, I am facing a requirement where the method getData() must consistently return a promise. Should data be present in local storage and not null, it should be returned as a promise without requiring the $http.get func ...

Using JavaScript parameters in a HTML document

I am trying to replicate a page similar to this. The issue I am facing is the inability to use external JS files in ASP.net (as far as I know). Therefore, I am defining the functions and attempting to utilize them within the HTML page instead. <%@ P ...

Create a spectrum of vibrant colors depending on the numerical value

I'm attempting to create a function that generates rainbow colors based on a numerical value. var max = 10000; var min = 0; var val = 8890; function getColor(min, max, val) { // code to return color between red and black } Possible Colors: Re ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...

Typescript's Array extension causes issues with constructors

During my experimentation with TypeScript, I encountered an interesting behavior: class ExtArray<U> extends Array<U> { constructor(...args : U[]) { super(...args); } public contains(element : U) : boolean { var i ...

Create a unique bar chart plugin using Javascript/jQuery that allows users to drag and drop data

My current project involves developing a custom bar chart generator that must meet specific criteria: Input fields for entering data to display on the chart The ability to drag and resize bars once the chart is generated I've conducted research and ...

What is the best way to convert the value of "range" to floating point numbers in JavaScript?

Why is it that when I input a float number, like "3.4567890", as the value in an input field, it automatically gets converted to type 'int'? This conversion is not desired, as I want the value to remain as a 'number' or 'float&apos ...

Stop repeated form submissions in Angular using exhaust map

How can we best utilize exhaust Matp to prevent multiple submissions, particularly when a user is spamming the SAVE button? In the example provided in the code snippet below, how do we ensure that only one submission occurs at a time even if the user click ...

One text label to display for a MultiLineString using MapLibre GL JS

I am attempting to show text labels for MultiLineString features within a geoJSON file using MapLibre GL JS. By utilizing the symbol-placement: point option, I aim to display the labels across various zoom levels rather than only when extremely close, as w ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...

The function is not defined, even though it is located within the same file

I've encountered an issue with my web page where I'm trying to read data from an HTML data table and update it on a PHP file using AJAX queries in JavaScript. Everything was working fine until recently, even though I didn't make any signific ...

Display the option to "Delete" the link only when there are multiple images in my image collection

I am using jQuery and Ajax to remove banner images from my website. However, I want to make sure that if there is only one image left, it cannot be deleted. Each image in the list has a corresponding delete link: echo '<a class="delete j_bannerd ...

Exploring IP geolocation integration within Rails 3

I am looking to add a dynamic feature to my homepage that will display the location object closest to the reader's physical location. Currently, I have a Location model with longitude and latitude fields. My goal is to retrieve the location model obj ...