如何在TypeScript中导出对象? [英] How do I export an object in TypeScript?

查看:76
本文介绍了如何在TypeScript中导出对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我正在尝试导出TS对象以获取此JavaScript输出:

For example, I'm trying to export a TS object to get this JavaScript output:

const path = require('path'),
      rootPath = path.normalize(__dirname + '/..'),
      env = process.env.NODE_ENV || 'development';

let config = {
  development: {
    amqpUrl: "amqp://localhost:15672",
    root: rootPath
    
  },
  test: {
    amqpUrl: "amqp://localhost:5672",
    root: rootPath
  
  },
  production: {
    amqpUrl: "amqp://localhost:5672",
    root: rootPath

  }
};
module.exports = config[env];

这是我的TS,但是导出时不清楚,

This is my TS, but it's not clear with exporting,

import path = require("path")
    
    const rootPath = path.normalize(__dirname + '/..')
    const env = process.env.NODE_ENV || 'development'
    
    let config = {
      development: {
        amqpUrl: "amqp://localhost:15672",
        root: rootPath
        
      },
      test: {
        amqpUrl: "amqp://localhost:5672",
        root: rootPath
      
      },
      production: {
        amqpUrl: "amqp://localhost:5672",
        root: rootPath
    
      }
    };

   /* this is the line i'm having problem how can i export config object*/
    // export config[env];

我已经尝试过 export default config [env] ,但是不会期望它生成的输出.我在做什么错了?

I've tried export default config[env] but its generated output isn't expected. What am I doing wrong?

推荐答案

在ES6中,允许使用导出功能导出名称,或者默认情况下,您可以导出任何内容. require 格式如下:

In ES6 you are allowed to export names using the export function, or for default you can export anything. The require format goes like this:

let config = require('config')

它采用默认导出配置文件.对于您的情况,您应该执行以下操作:

And it takes the default export of config file. In your case, you should do:

export default config[env]

如果要使用导出,请执行以下操作:

If you want to use the export, you would do something like:

let Environment = config[env];
export {Environment}

区别将是:

import EnvirmentNameWhatever from "./config"

import {Environment} from "./config"

  • 注意-默认导出时,您可以使用任何喜欢的名称,而仅导出时,则必须使用导出的名称.
  • 这篇关于如何在TypeScript中导出对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆