如何从 javascript 文件中的打字稿文件导入对象?

How to import object from typescript file in javascript file?

我有constants.ts个文件:

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

我需要在我的 .js 脚本文件中导入 script.js 以某种方式从 contsants.ts 导入:

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:

目标:您想从常量中注销文档。

到达那里的步骤:

  • 使用 TypeScript tsc.ts 编译为 .js
  • 现在使用来自您的 js 文件的已编译 .js 文件

示例:

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

最后这样做了:

// 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])
}