Saurabh Sinha
Saurabh Sinha

Reputation: 1800

Trying to import a class written in typescript to javascript NodeJs showing error

I am creating a node express application. For my use case, I have a 1.ts file with a class as:

export class blah {
    constructor(props) {

    }
    tt() {
      console.log('logging function');
    }
}

in my 2.js file i am importing as

const blah = require('./1')
var b = new blah.blah()
console.log(b.tt())

But nothing in console.function is not being called.

How do i fix this problem. tsconfig.json file content

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
   "sourceMap": true,
   "experimentalDecorators": true,
   "emitDecoratorMetadata": true
  },
 "exclude": [
"node_modules"
 ]
}

Upvotes: 0

Views: 581

Answers (2)

steven.westside
steven.westside

Reputation: 284

I am posting as an answer to post the contents of the files. This code works for me. I am running just the command tsc in the directory with the files. Output files are 1.js and 1.js.map. Then I run node 2. The output is

logging function
undefined

(On a sidenote: It prints undefined because the call console.log(b.tt()) tries to print the return value of b.tt(), but it does not return anything)

const blah = [...] gives me the same error you got.

Directory structure (everything on the same level):

  • 1.ts
  • 2.js
  • tsconfig.json

1.ts

export class blah {
    constructor(props) {

    }
    tt() {
      console.log('logging function');
    }
}

2.js

const {blah} = require('./1')
var b = new blah()
console.log(b.tt())

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "sourceMap": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    },
    "exclude": [
        "node_modules"
    ]
}

Upvotes: 1

abhijeet abanave
abhijeet abanave

Reputation: 133

It must be const blah = require("./1")

Upvotes: 1

Related Questions