Quick method for executing TypeScript files

Overview

Currently, I am running a TypeScript program from this repository.

node --loader ts-node/esm ./examples/ts/cli.ts bitget fetchBalance

The TypeScript version of this program takes significantly longer to run compared to the JavaScript version.

node --loader ts-node/esm ./examples/ts/cli.ts   bitget fetchBalance  14.73s user 0.60s system 153% cpu 10.010 total
node                      ./examples/js/cli.js   bitget fetchBalance  0.49s  user 0.07s system 14%  cpu 3.756  total

I am exploring ways to reduce the runtime of this program and one area I am investigating is the way in which TypeScript is being executed.


TSX Error

Prior to executing a git reset --hard, TSX was functioning properly. However, after the reset, I encountered the following error despite having installed JSBN:

% tsx ./examples/ts/cli.ts bitget fetchBalance
node:internal/errors:484
ErrorCaptureStackTrace(err);
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/.../ccxt/ts/src/static_dependencies/jsencrypt/lib/jsbn/jsbn.js' imported from /.../ccxt/ts/src/static_dependencies/jsencrypt/lib/jsrsasign/asn1-1.0.js
    at __node_internal_captureLargerStackTrace (node:internal/errors:484:5)
    at new NodeError (node:internal/errors:393:5)
    ...
Node.js v18.12.0

ts-node Issue

Attempting to use ts-node resulted in the following error:

 % ts-node ./examples/ts/cli.ts bitget fetchBalance
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /.../ccxt/examples/ts/cli.ts

Solution Suggestions from Stack Overflow

Issue with Solution 1

If I remove

"type": "module",
from package.json, it leads to another error:

import fs from 'fs';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Problem with Solution 2

  "compilerOptions": {
    "esModuleInterop": true,
  }

This setting already exists in my tsconfig.json file.

  • These issues occur when using ts-node or ts-node-esm

ts-node-esm Challenge

When attempting to utilize tsx-node-esm, I encountered the following errors:

 %  ts-node-esm ./examples/ts/cli.ts bitget fetchBalance        
/usr/local/lib/node_modules/ts-node/src/index.ts:859
...
}

Answer №1


Speed up your web compilation with SWC!

Here are the steps to utilize SWC efficiently:

  1. Begin by installing SWC:

    Simply run npm install --save-dev @swc/cli

  2. Transpile your TypeScript file using SWC:

    Execute swc your-file.ts --outfile output.js

  3. Finally, run the JavaScript file that was generated:

    Just type node output.js in your terminal


Try out esbuild for fast building of your projects

Follow these steps to implement esbuild seamlessly:

  1. Start off by installing esbuild:

    Easily install it via npm: npm install --save-dev esbuild

  2. Utilize esbuild to run your TypeScript files:

    Type npx esbuild --bundle --platform=node your-file.ts in your console


Enhance your workflow with esbuild-runner

Here's how you can integrate esbuild-runner into your projects:

  1. Install both esbuild and esbuild-runner:

    Get them through npm with: npm install --save-dev esbuild esbuild-runner

  2. Run your TypeScript file smoothly:

    Execute node -r esbuild-runner/register your-file.ts


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

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

Adding an Icon to the Angular Material Snackbar in Angular 5: A Step-by-Step Guide

I recently started using Angular and have incorporated Angular Material Design for my UI elements. Within my application, I am utilizing a snackbar component. However, I am facing difficulty in adding an icon inside the snackbar despite trying various so ...

How can the action value be passed in effects for switchMap using both another switchMap and filter?

There is a certain code snippet @Effect() myEffect$ = this.actions$.pipe( ofType(MyActions.doSomething), tap(() => this.store.dispatch(MyActions.doSomething2())), switchMap(action => { that is functioning as expected. In order to inj ...

Choose a single asset from the list of values stored in the Map

I'm looking to implement something similar to the following: let myMap = new Map<string, any>(); myMap.set("aaa", {a: 1, b: 2, c:3}); myMap.set("bbb", {a: 1, b: 2, c:6}); myMap.set("ccc", {a: 1, b: 2, c:9}); let cs = myMap.values().map(x => ...

Issues with TypeScript Optional Parameters functionality

I am struggling with a situation involving the SampleData class and its default property prop2. class SampleData { prop1: string; prop2: {} = {}; } export default SampleData; Every time I attempt to create a new instance of SampleData without sp ...

Encountering an issue saving files in Angular 2 when the npm server is active

Encountering an issue when trying to save .ts or .html files while npm is running 1: DoJoin(aka DoJoin) [native array.js:~129] [pc=0000035BB365DBB2] (this=0000005A3F604381 <undefined>,w=000003CB8840CFF1 <JS Array[104]>,x=104,N=0000005A3F6 ...

The error message is: "Cannot access property 'up' of an undefined object within the material UI library using theme.breakpoints."

I am encountering difficulties with the export of makeStyles. Below you can find my code and configuration: import SearchField from "../SearchField"; import { TextField, Select, useMediaQuery, Grid, Button, Box, Fade } from '@material-ui/core&ap ...

Embracing the "export ... from" feature in the TypeScript compiler

Can the tsc compiler handle this particular export statement? export {PromiseWrapper, Promise, PromiseCompleter} from 'angular2/src/facade/promise'; Your assistance is greatly appreciated! ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

"Utilizing the power of Angular 6's JSON pipe

Looking for a well-structured formatted JSON, but all I get is confusion and this strange image: https://i.sstatic.net/6mvBu.png Does anyone have any insights on what might be causing the issue? HTML <span style="font-weight: 500;">Payload Data: ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Having trouble with react-i18next not working properly in my React Native application

I recently initiated a new react-native project, but I seem to be encountering an issue with my react-i18next translations. Despite having the keys correctly set up, I am unable to view the translations. Furthermore, I have noticed that my components are ...

Troubleshooting the createStyles Problem in Material UI with Typescript

I am currently working on implementing a test code following the guidelines provided in the Material UI typescript documentation. import * as React from 'react'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; import ...

Customized Generic Types in TypeScript based on optional property conditions

In my React/Typescript app, I currently have the following code snippet - export type GetPricingParams = { search_id: number, promo_code?: string, }; export type GetPricingData = { amount: number, currency: string, search_id: number, ...

The issue of binding subjects in an Angular share service

I established a shared service with the following Subject: totalCostSource$ = new Subject<number>(); shareCost(cost: number ) { this.totalCostSource$.next(cost); } Within my component, I have the following code: private incomeTax: num ...

Developed a customized checkbox component using React

I encountered an issue while creating a custom checkbox in React. I was able to successfully create it, but faced difficulty in reverting it back to its original state once checked. The values for checked and unchecked are being fetched from a JSON data. ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

UI-Router - issue with query parameters preventing arrays with only one item

My application utilizes UI-Router, specifically with a state named Widgets that includes a query parameter accepting an array of widgets: const widgetsState = { name: "widgets", url: "/widgets?{widgets:string[]}", component: Widgets, pa ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...