如何在Typescript中导出对象 [英] How to export object in Typescript

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

问题描述

我正在将现有的JavaScript项目转换为类型脚本。我不知道如何导出对象来获取这个javscript输出

I'm converting existing JavaScript project into type script. im not sure how to export object to get this javscript 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];

我写的打字稿如下,但不清楚导出

i wrote typescript as follow but 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];

当我导出时如何导出我试过的对象导出默认配置[env] 但它会从预期输出中产生一些差异

when i exporting how can i export just object i tried with export default config[env] but it generates something deference from expected output

推荐答案

在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天全站免登陆