【问题标题】:react-loadable gives a 404 error whenever I go to the route where the specific component is used每当我转到使用特定组件的路线时,react-loadable 都会出现 404 错误
【发布时间】:2018-07-27 13:52:34
【问题描述】:

到目前为止,我一直在尝试对我的概念网站进行代码拆分,但它似乎不起作用。我有一个 STLMain 组件(STLMain.js):

import React from 'react';

export default () => (
  <div>
    STLMain
  </div>
);

在 STLMainLoadable.js 中使用:

import React from 'react';
import Loadable from 'react-loadable';

const loading = () => (
  <div>
    Loading...
  </div>
);

export default Loadable({
  loader: () => import('./STLMain'),
  loading
});

然后在我的 Router.js 中使用它

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Home from './main_pages/Home';
import NotFound from './main_pages/NotFound';
import STLMainLoadable from './main_pages/STLMainLoadable';
import Navigation from './navigation/Navigation';

export default () => (
  <BrowserRouter>
    <div>
      <Navigation />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/STLMain" component={STLMainLoadable} />
        <Route component={NotFound} />
      </Switch>
    </div>
  </BrowserRouter>
);

每次我访问 localhost:8080/STLMain 时,我都会在控制台中收到两个错误:

1.GET http://localhost:8080/0.bundle.js 404(未找到)
2.拒绝从'http://localhost:8080/0.bundle.js'执行脚本,因为它的MIME类型('text/html')不可执行,并且启用了严格的MIME类型检查。

是的,我安装了 syntax-dynamic-import babel 插件。 我该怎么做才能解决这个问题?

【问题讨论】:

  • 似乎代码拆分工作正常,您可能在服务资源时遇到问题。尝试在浏览器中直接加载localhost:8080/0.bundle.js(或您拥有的任何名称)。我认为您没有提供 JavaScript。您使用的是 yarn 开发服务器还是...?
  • 我正在使用 webpack 开发服务器
  • 如果我转到localhost:8080/0.bundle.js,它会说:“Cannot GET /0.bundle.js”

标签: javascript reactjs react-router


【解决方案1】:

如果您还没有,请尝试在您的webpack.config.js 中设置output.publicPath = '/'

output: {
  ...
  publicPath: '/',
  ...
}

Credit where credit is due

【讨论】:

  • 是的,它可以工作,但是你必须写下一个 url 而不是 root publicPath: "/",你的静态文件是由你的服务器提供的。就我而言,它是“/static/js”
猜你喜欢
  • 2016-09-08
  • 2020-01-21
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 2020-05-18
  • 1970-01-01
相关资源
最近更新 更多