Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
}
like image 839
timstermatic Avatar asked Apr 28 '18 11:04

timstermatic


1 Answers

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.

like image 120
timstermatic Avatar answered Nov 02 '22 22:11

timstermatic