Gayane
Gayane

Reputation: 567

webpack 2 fails to import files with dynamic path with react router

I've just start using webpack, I'm using react router with dynamic page loader, and want to import my files dynamically, but getting this warning in webpack:

WARNING in ./apps/pages/routes.js 35:6-44 Critical dependency: the request of a dependency is an expression

here are my code examples:

const routes = {
  component: App,
  childRoutes: [
    {
      path: '/',
      getComponent (location, cb) {
        System.import('./Home')
          .then(loadRoute(cb))
          .catch(errorLoading)
      }
    },
    {
      path: 'about',
      getComponent (location, cb) {
        System.import('./About')
          .then(loadRoute(cb))
          .catch(errorLoading)
      }
    }
  ]
}

this works fine, but when I want to make it with variables like this:

const routersPaths = [
  {path: '/', filePath: './Home'},
  {path: 'about', filePath: './About'}
]

const childRoutes = routersPaths.map(childRoute => {
  return {
    path: childRoute.path,
    getComponent (location, cb) {
      System.import(childRoute.filePath)
        .then(loadRoute(cb))
        .catch(errorLoading)
    }
  }
})

const routes = {
  component: App,
  childRoutes: childRoutes
}

it fails. I'm wondering is there a way to make this work?

Upvotes: 0

Views: 127

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 33010

It is not possible to use a variable as argument to import. Webpack needs to know what modules to include at compile time, and it does no program flow analysis, so it won't be able to know which ones to include. In your case it might be easy to determine, but it could go much further as you could construct the import path at will during run time, so it's not allowed by webpack at all.

There is an exception, you can use a concatenated string, but that will add all modules to the bundle that match the expression, even if they aren't used, as shown in require with expression (the same rules apply to both import and require). But that approach should be avoided.

By the way, System.import is deprecated and has been replaced with import() (the function).

Upvotes: 1

Related Questions