React.lazy error Object(...) is not a function

Viewed 7737

I'm trying to Lazy Load the App component. I've read the React doc samples and have come up with the solution below. However, I get a TypeError: Object(...) is not a function and I'm not sure why. I've also tried doing import('').default.

import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

// import { App } from './components/navigation';
// import Login from './components/login/LoginContainer';
import PrivateRoute from './components/privateRoute/PrivateRoute';
import HTML5Backend from 'react-dnd-html5-backend';
import { DragDropContext } from 'react-dnd';
import { Redirect } from 'react-router';

const Login = lazy(() => import('./components/login/LoginContainer'));
const App = lazy(() => import('./components/navigation/AppContainer'));

const Main = () => {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route name="login" exact path="/login" component={Login} />
          <Route name="loginWithTripId" exact path="/login/:tripid" component={Login} />
          <PrivateRoute path="/trips/:tripid" component={App} />
          <PrivateRoute path="/trips/dashboard" component={App} />
          <Route render={() => <Redirect to={'/login'} />} />
        </Switch>
      </Suspense>
    </BrowserRouter>
  );
};

export default DragDropContext(HTML5Backend)(Main);

For some reason React.lazy is undefined if I console.log it... I've tried removing node_modules and doing npm install again with no success

3 Answers

In a development server, using for example webpack-dev-server, you have to use:

const Login = lazy(() => import('./components/navigation/LoginContainer')); ... <Route name="login" exact path="/login" component={props => <Login {...props} />} /> ...

and it will works also in a production environment.

Ok so I managed to get it fixed by turning off my development server and restarting using npm start.

Related