2

I am trying to import component using import(). It is giving me error.

I am using react-loadable I tried with react-import package as well but no luck

I tried with below code:

import React, { Component } from 'react';
import { HashRouter, Route, Switch } from 'react-router-dom';
import Loadable from 'react-loadable';
import './App.scss';

const loading = () => <div className="animated fadeIn pt-3 text-center">Loading...</div>;


// Containers
const DefaultLayout = Loadable({
  loader: () => import('./containers/DefaultLayout'),
  loading
});

Attached Error Screenshot

Module build failed: SyntaxError: ...../resources/assets/js/src/App.js: Unexpected token, expected { (5:7)

Any help would be appreciated

3
  • 1
    Check whether you have babel-loader and the dependencies installed, it can be the issue. Commented Dec 12, 2018 at 18:00
  • Use require() instead of import(). Commented Dec 12, 2018 at 18:00
  • require() does work but now other react syntax is having an issue like const loading = () => .. is not valid syntax. @AbhishekKumawat I will chek other alternatives. Commented Dec 12, 2018 at 18:16

2 Answers 2

1

I have a custom Webpack/Babel config for my React application, in my situation I needed to install:

npm i @babel/plugin-syntax-dynamic-import

And then I needed to add one line to my package.json file under "babel" > "plugins":

"babel": {
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
},
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add support for the dynamic import syntax.

Babel has a plugin for this called @babel/plugin-syntax-dynamic-import
https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import

Install the plugin with:
yarn add -D @babel/plugin-syntax-dynamic-import -D
or
npm install --save-dev @babel/plugin-syntax-dynamic-import


Then:
The Babel recommendation is to add the plugin to your .babelrc file like:

{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

Comments

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.