Dynamic imports in Jest produce: SyntaxError: Unexpected token import

2.9k Views Asked by At

Can't figure out how to resolve these errors yet, Jest is complaining about dynamic imports like these:

const importModules = Promise.all([
      import('containers/HomePage/reducer'),
      import('containers/HomePage/sagas'),
      import('containers/HomePage'),
    ]);

Error message:

F:\react-boilerplate\app\store.js:49
      import('./reducers').then(function (reducerModule) {
      ^^^^^^
SyntaxError: Unexpected token import

You can find all of the details here: https://github.com/mxstbr/react-boilerplate/pull/1358

2

There are 2 best solutions below

1
Dattaya On BEST ANSWER

Installing babel-plugin-dynamic-import-node solved our problem. In addition, make sure that babylon (babel dependency) is at least 6.12.0.

Also, we had a problem with Travis build because Travis cached node_modules and old babylon with it:

$ npm ls babylon
[email protected] /home/travis/build/mxstbr/react-boilerplate
├─┬ [email protected]
│ └── [email protected]
├─┬ [email protected]
│ └── [email protected] 
├─┬ [email protected]
│ └─┬ [email protected]
│   └── [email protected] 

, so we had to turn the cache off with: cache: false

0
Andreas Köberle On

It looks like jest cant compile your files with the babel settings for test in your .babelrc file. You need to have the same settings for prod and test