1

I have created one React App using npx create-react-app my-app cmd (React 17 version). Now Well, I just tried to replace a classic

import Component from './Component'

to

const Component = React.lazy(() => import('./Component'));

and then

<React.Suspense fallback={<div>Loading.. </div>}>
    <Component />
</React.Suspense>

but it throws error like SyntaxError: Unexpected token at import(6:22)

> 6 |  const Component = React.lazy(() => import('./Component'));

Can anyone help me to resolve this?

This is the code syntax enter image description here

And this is the suspense component enter image description here

And this is the compilation output enter image description here

My package.json looks like

enter image description here

3
  • I have a full routing file with every component is imported using React.lazy and its a create react app and i am also using React.Suspense and its working completely fine. are you importing React right? :p other than that it might be a type or syntax error Commented Feb 5, 2021 at 12:43
  • Please check I have updated the question with my exact code and some snapshots. Commented Feb 5, 2021 at 13:05
  • Do we need any extra setup to solve this? Commented Feb 5, 2021 at 13:07

1 Answer 1

0

I'm not sure, if this fixes your issue, but maybe you can give it a try. Are you using Babel?

It says:

When using Babel, you’ll need to make sure that Babel can parse the dynamic import syntax but is not transforming it. For that you will need @babel/plugin-syntax-dynamic-import.

https://reactjs.org/docs/code-splitting.html#import

I've created a .babelrc file on the project root and added the content:

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

I also imported lazy in my component:

import React, { Component, lazy, useEffect, useState } from 'react';

In my project React.lazy is working fine this way.

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

3 Comments

Let me check this and will back to you.
No, I am not using babel
Created react app using create-react-app cmd

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.