简体   繁体   English

导入常量未定义 Javascript 反应原生

[英]Import constants undefined Javascript react native

I'm building a react native module and I want to export a file of constants that can be used.我正在构建一个反应原生模块,我想导出一个可以使用的常量文件。

I have a file, MyConstants.js which looks like this:我有一个文件MyConstants.js ,它看起来像这样:

export const MyConst = “testConst”;

Then I have an index.js file for my module:然后我的模块有一个index.js文件:

module.exports = {

  get MyConstants() {
    return require('./MyConstants');
  },

};

When I import my constants as: import * as MyConstants from 'myPackage';当我将常量导入为: import * as MyConstants from 'myPackage'; and print them I get打印出来我得到

console.log(MyConstants); // [object Object]
console.log(MyConstants.MyConst); // undefined

This approach works fine when being used from within my module with:这种方法在我的模块中使用时效果很好:

import * as MyConstants from './MyConstants.js';

But when I try to use it from outside I get issues.但是当我尝试从外部使用它时,我遇到了问题。 How can I fix this?我怎样才能解决这个问题?

In MyConstants.js you can do something like this:MyConstants.js ,您可以执行以下操作:

export const CONST_1 = 'test const 1';
export const CONST_2 = 'test const 2';
export const CONST_3 = 'test const 3';
.
.
.

And then in index.js you can do:然后在index.js中你可以这样做:

import * as MyConstants from './path_to/MyConstants.js';

console.log(MyConstants.CONST_1) //outputs: test const 1
console.log(MyConstants.CONST_2) //outputs: test const 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM