简体   繁体   中英

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"
 ]
}

它必须是 const blah = require("./1")

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"
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM