dynamic async import (require.ensure) should work on server side

What is the current behavior?

If the current behavior is a bug, please provide the steps to reproduce.

import('./pages/' + pageName + '.jsx').then(module => cb(null, module.default)).catch(ex => console.error(ex));

Throws: TypeError: webpack_require.e is not a function on node.js

A workaround is:

  if (IS_BROWSER) {
    return (nextState, cb) => {
      import('./pages/' + pageName + '.jsx').then(module => cb(null, module.default)).catch(ex => console.error(ex));
    }
  } else {
    return (nextState, cb) => {
      require('./pages/' + pageName + '.jsx');
    }
  }

What is the expected behavior?
The import function (same for the deprecated functions require.ensure, System.import) should work natively on server side when target is “node”.

If this is a feature request, what is motivation or use case for changing the behavior?

Node.js version: 7
Webpack version: 2.1, 2.2

Author: Fantashit

1 thought on “dynamic async import (require.ensure) should work on server side

  1. So I’ve been working closely with import() and have a couple notes to contribute to this thread:

    1. Node will complain about import(), but can be re-written to require.ensure() using the ‘dynamic-import-node’ babel plugin

    2. Including ‘dynamic-import-node’ in .babelrc will cause code-splitting not to work, so I start my server using babel-node server.js --plugins=dynamic-import-node so it used only for the server, and the client code will be left alone and continue to use import() instead of require.ensure

    3. When using eslint, Webpack 2 itself (not eslint, interestingly enough), will say:
      Parsing error: ‘import’ and ‘export’ may only appear at the top level

    The dynamic import() in react-router getComponent() handlers is being treated the same as a static import statement, and therefore the parsing error occurs.

    I know this is a recent change, going from System.import() to import(), so I just wanted to share my findings in case anyone else is encountering these issues.

Comments are closed.