8

I'm attempting to refactor a growing React App to use lazy loading. Taking the following as an example:

import React, { Component } from 'react'
import { render } from 'react-dom'
import Loadable from 'react-loadable';

const Orders = Loadable({
    loader: () => import('./Orders'),
    loading() {
        return <div>Loading...</div>
    }
});

My webpack compile always fails with:

Module build failed: SyntaxError: Unexpected token
...
> 24 |   loader: () => import('./Orders'),

It's clearly the import that is choking the code, but I don't understand why.

My .babelrc file looks like this:

{
  "presets": ["env", "react"]
}
6
  • What webpack version do you use? Commented Apr 28, 2018 at 11:14
  • does it work if you use require instead of import? Commented Apr 28, 2018 at 11:15
  • 1
    The import(...) syntax is Stage 3, are you sure you have the necessary options/plugins for it to work in your setup? Commented Apr 28, 2018 at 11:16
  • @TomaszMularczyk 4.6 Commented Apr 28, 2018 at 17:18
  • @riwu I don't think this will work, I need to use import Commented Apr 28, 2018 at 17:18

1 Answer 1

13

So following up on T.J. Crowder's comment to my original question I found the babel dynamic import plugin

Installing this with yarn:

yarn add babel-plugin-syntax-dynamic-import -dev

Then adding it to my .babelrc, thus:

{
    "presets": ["env", "react"],
    "plugins": ["syntax-dynamic-import"]
}

fixed the Unexpected token issue.

Sign up to request clarification or add additional context in comments.

1 Comment

yarn save dev function is used adding a -D at the end of the line, not -dev

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.