简体   繁体   English

React 基于路由的代码拆分导入 Unexpected token 错误

[英]React Route-based code splitting import Unexpected token error

import React, {Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const HomePage = lazy(() => import('../../layouts/Home/Home'));
const Routes = () => (
            <Router>
              <Suspense fallback={<div>Loading...</div>}>
                <Switch>
                  <Route exact path="/" component={HomePage}/>
                </Switch>
              </Suspense>
            </Router>
        );
export default Routes;

enter image description here在此处输入图像描述

i have create react project and import class component using react lazy import not working.我已经创建了反应项目并使用反应延迟导入不起作用导入 class 组件。

Please help me.请帮我。

Checkout this post It explains how to use lazy loading with react-router查看这篇文章它解释了如何使用 react-router 的延迟加载

The error looks like something is wrong with the import token, due to bable issue由于 bable 问题,该错误看起来像是导入令牌有问题

Try using require instead of import尝试使用 require 而不是 import

Example例子

import React, { Suspense, lazy } from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
const HomePage = lazy(() => Promise.resolve(require("../../layouts/Home/Home")));
const Routes = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={HomePage} />
      </Switch>
    </Suspense>
  </Router>
);
export default Routes;

render(<Routes />, document.getElementById("root"));

I think you need to add plugin to use dynamic import我认为您需要添加插件才能使用动态导入

You can use npm to install it可以使用npm来安装

npm install -D babel-plugin-syntax-dynamic-import

and then add it to your.babelrc as然后将其添加到 your.babelrc 作为

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

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM