0

I am using react-loadable to load the views. The code below works fine:

const Home = Loadable({
    loader: () =>
        import ('./views/home'),
    loading: Loading,
});

But I have multiple views, hence I want to generalize (refactor) the above code by replacing the path string with a variable. And that's where the problem starts. I tried following technique, but it doesn't load the target view, instead it just keeps the Loading view, which is just a temporary view containing simply 'Loading...' string.

const getLoadableView = (viewPath) => {
  return Loadable({
    loader: ((p) => {
      const m = p;
      return () => {
        console.log(m); //this one prints the correct value
        return import(m);
      };
    })(viewPath),
    loading: Loading
  });
}
const Home = getLoadableView('./views/home');

Am I missing something? Thanks.

Nadeem Jamali
  • 1,353
  • 3
  • 16
  • 27
  • Is `getLoadableView` declared in the same place (module) that `Home` is created in? – Bergi Sep 27 '18 at 18:33
  • You really need neither `m`, nor `p`, nor that IIFE. Just use `viewPath`. – Bergi Sep 27 '18 at 18:34
  • Yes, both are declared in same place. I tried without local variables too, but no luck. Can you come up with an example? – Nadeem Jamali Sep 27 '18 at 18:35
  • Try `.catch()`ing errors from the import. Also, in what environment are you running this? Do you use a transpiler and/or bundler? Does it support dynamic imports? – Bergi Sep 27 '18 at 18:39
  • The error it throws is: Cannot find module './views/home'. Where as if replace variable m in import call with the './views/home', it again works.... So, there is something weird happening in import call. – Nadeem Jamali Sep 27 '18 at 22:49
  • Again, do you use a transpiler/bundler? – Bergi Sep 28 '18 at 09:30
  • Yes, it is react-scripts, which uses webpack at it's core... – Nadeem Jamali Sep 28 '18 at 13:35

1 Answers1

0

I resolved this issue by the following trick:

const getLoadableView = (viewPath) => {
  return Loadable({
    loader: () => import(`./${viewPath}`);;
    })(viewPath),
    loading: Loading
  });
}
const homeViewPath = 'views/home';
const Home = getLoadableView(homeViewPath);

You can notice that I have done nothing special, but just partitioned the path in two parts. The first path is hardcoded in import call.

Obviously this is not a solid solution, but I could not find the actual reason behind such behaviour of import call.

Nadeem Jamali
  • 1,353
  • 3
  • 16
  • 27