1

I write a function which will load a file using require():

function loadFromName(name) {
  const filename = `./${name}.initialState`;
  return require(filename).default;
}

When I call this method, it will fail to find the file:

loadFromName('tab')

> Requiring unknown module "./tab.initialState". If you are sure the module is there, try restarting the packager or running "npm install".

I tried two kinds of inline require(). One is success; one is failed.

let initialState;
const name = 'tab';
initialState = require('./tab.initialState');   // success
const filename = './' + 'tab' + '.initialState';
initialState = require(filename);               // failed

Why and how to fix it?

NOTE: I use this in React-Native development

Xaree Lee
  • 3,188
  • 3
  • 34
  • 55
  • Have a look at this: http://stackoverflow.com/questions/17446844/dynamic-require-in-requirejs-getting-module-name-has-not-been-loaded-yet-for-c – Heinrich Nov 18 '16 at 03:44
  • Could you write an example of `function loadFromName()`, and I'll accept the answer. – Xaree Lee Nov 18 '16 at 05:44
  • Are you using require from node or requirejs, I was trying some code out and I can't replicate the issue you are having. What does your ./tab.initialState look like is it set up correctly? – Heinrich Nov 20 '16 at 23:05

1 Answers1

1

Dynamic require is not supported on react native. There are lot of similar questions on stack overflow React Native - Image Require Module using Dynamic Names

Community
  • 1
  • 1
agenthunt
  • 8,450
  • 3
  • 30
  • 26