Ad

Unexpected Token When Lazy Loading Components

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"]
}
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad