Is it possible to write TypeScript and execute it directly with Node?

I am attempting to write some basic typescripts but I am encountering an issue with the setup below:

node src/getExchangeAndTickerList.ts

import * as mkdirp from 'mkdirp';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1047:16)
    at Module._compile (internal/modules/cjs/loader.js:1097:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)
    at Function.Module._load (internal/modules/cjs/loader.js:877:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
{
  "compilerOptions": {
    "module": "commonjs",
      "target": "ES2018",
      "moduleResolution": "node",
      "baseUrl": ".",
      "paths": {
          "*": [ "./*" ],
      },
      "types": ["node"]
  },    
  "include": [
      "./src/**/*.ts",
  ],
  "exclude": [
    "./node_modules"
  ]
}

Answer №1

By default, Vanilla node can only interpret and execute Javascript code. If you need to work with Typescript code, there are a couple of solutions available:

  • One option is to utilize a tool like ts-node that registers .ts files.
  • Another approach is to transpile your Typescript code by running the tsc command, which will convert your code into Javascript files.

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

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

Monaco Editor in TypeScript failing to offer autocomplete suggestions

When using a union type as a parameter of a function in Monaco Editor, the suggestions do not appear. However, in VS Code, the suggestions are provided. Is there a setting I need to enable in Monaco to have the same functionality? Although Monaco provides ...

Analysis of cumulative revenue using Palantir Foundry Function

I am in need of creating a function that can transform raw data into target data. The raw data consists of a table with columns for customer, product, and revenue, while the target data includes customer, revenue, and cumulative revenue. customer produ ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

How to implement ngx-infinite-scroll in Angular 4 by making a vertically scrollable table

Looking for a way to make just the table body scrollable in Angular 4 using ngx-infinite-scroll. I've tried some CSS solutions but haven't found one that works. Any help or documentation on this issue would be greatly appreciated. I attempted th ...

The button click function is failing to trigger in Angular

Within my .html file, the following code is present: The button labeled Data Import is displayed.... <button mat-menu-item (click)="download()"> <mat-icon>cloud_download</mat-icon> <span>Data Imp ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

Leveraging Firestore Errors within Cloud Functions

Is it possible to utilize the FirestoreError class within Firebase cloud functions? The goal is to raise errors with a FirestoreError type when a document or field is not found in Firestore: throw new FirestoreError(); Upon importing FirestoreError using ...

The module 'crypto-js' or its corresponding type declarations cannot be located

I have a new project that involves generating and displaying "QR codes". In order to accomplish this, I needed to utilize a specific encoder function from the Crypto library. Crypto While attempting to use Crypto, I encountered the following error: Cannot ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

Issue with package: Unable to locate the module specified as './artifacts/index.win32-ia32-msvc.node'

I am encountering an issue while using Parcel for the first time. When I execute npx parcel .\app\index.html, I receive the following error: Error: Module not found './artifacts/index.win32-ia32-msvc.node' Require stack: - C:\Users ...

Connecting an Angular 4 Module to an Angular 4 application seems to be causing some issues. The error message "Unexpected value 'TestModule' imported by the module 'AppModule'. Please add a @NgModule annotation" is

Update at the bottom: I am currently facing a massive challenge in converting my extensive Angular 1.6 app to Angular 4.0. The process has turned into quite a formidable task, and I seem to be stuck at a specific point. We have a shared set of utilities th ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

Testing a function that utilizes Nitro's useStorage functionality involves creating mock data to simulate the storage behavior

I have developed a custom function for caching management, specifically for storing responses from API calls. export const cache = async (key: string, callback: Function) => { const cacheKey = `cache:${key}`; const data = await useStorage().get ...

Developing personalized middleware definition in TypeScript for Express

I have been struggling to define custom middleware for our application. I am using [email protected] and [email protected]. Most examples of typing middleware do not involve adding anything to the req or res arguments, but in our case, we need to modify ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...