简体   繁体   中英

How to import object from typescript file in javascript file?

I have constants.ts file:

    export const docs = {
      "0x1": {id: "1"},
      "0x2": {id: "2"}
    }

And i need to import in my .js script file script.js import from contsants.ts somehow:

console.log(import from contants.ts)

    {
      "0x1": {id: "1"},
      "0x2": {id: "2"}
    }

And i need to import in my .js script file script.js import from contsants.ts somehow:

Target: You want to log out docs from constants.

Steps to get there:

  • Compile your .ts to .js using TypeScript tsc .
  • Now use the compiled .js file from your js file

Example:

const constants = require('./constants'); 
console.log(constants.docs); // Prints as required.

Ended-up doing this:

// script.js

const filecontent = fs.readFileSync(PATH_TO_TS_FILE, {encoding: 'utf-8'})
const contracts = JSON.parse(filecontent.replace('export const docs = ', '').replace(/id:/g, '"id":'))

for(key in contracts) {
   console.log(contracts[key])
}

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