Shih-Min Lee
Shih-Min Lee

Reputation: 9690

React native require relative path file

I am trying React Native iOS and I was trying to setup project environments. I create a file called config.js so later I can just

import config from 'env'

to load the variables based on different environments. The following is the config.js file

let configFile = 'dev.js'
if (NODE_ENV === 'production') {
  configFile = 'prod.js'
}

export default require('./env/' + configFile)

Somehow this won't work. the error message is:

Requiring unknown module "./env/dev.js". If you are sure the module is there, try restarting the packager or running "npm install"

When I changed my code to the following it would not give me errors. But it is not what I wanted to do.

export default require('./env/dev.js')

So does anyone know why is that?

Upvotes: 0

Views: 1195

Answers (1)

agenthunt
agenthunt

Reputation: 8678

Firstly, require calls are not dynamic. They are statically analyzed and bundled. So you would want something like this

let prodConfig = require('./env/prod.js');
let devConfig = require('./env/dev.js');

let config;
if (process.env.NODE_ENV === 'production') {
  config = prodConfig;
}else {
  config = devConfig;
}

export default config;

Upvotes: 1

Related Questions