[英]How do I export an object in TypeScript?
For example, I'm trying to export a TS object to get this JavaScript output:例如,我试图导出一个 TS 对象以获取此 JavaScript 输出:
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];
This is my TS, but it's not clear with exporting,这是我的TS,但是导出不清楚,
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];
I've tried export default config[env]
but its generated output isn't expected.我试过
export default config[env]
但它生成的输出不是预期的。 What am I doing wrong?我究竟做错了什么?
In ES6 you are allowed to export names using the export function, or for default you can export anything.在 ES6 中,您可以使用导出功能导出名称,或者默认情况下您可以导出任何内容。 The
require
format goes like this: require
格式如下:
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}
The difference would be:不同之处在于:
import EnvirmentNameWhatever from "./config"
to到
import {Environment} from "./config"
Using the export
keyword on the declarations to export should do the job, like this:在要
export
的声明上使用export
关键字应该可以完成这项工作,如下所示:
import path = require("path")
const rootPath = path.normalize(__dirname + '/..')
export const env = process.env.NODE_ENV || 'development'
export let config = {
development: {
amqpUrl: "amqp://localhost:15672",
root: rootPath
},
test: {
amqpUrl: "amqp://localhost:5672",
root: rootPath
},
production: {
amqpUrl: "amqp://localhost:5672",
root: rootPath
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.