Xaree Lee
Xaree Lee

Reputation: 3397

JavaScript fails to require a file from a concat string

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

Upvotes: 1

Views: 3581

Answers (1)

agenthunt
agenthunt

Reputation: 8678

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

Upvotes: 1

Related Questions