从 cdn 反应惰性导入

React lazy import from cdn

我正在遵循使用 React Router 和 Suspense 进行延迟加载的指南:

https://itnext.io/async-react-using-react-router-suspense-a86ade1176dc

这是我目前的代码:

import React, { lazy, Suspense } from 'react';
import { Link, Route, BrowserRouter as Router, Switch } from 'react-router-dom';

const HomePage = (
  lazy(() => (
    import('./pages/HomePage')
  ))
);

const BookingsPage = (
  lazy(() => (
    import('./pages/BookingsPage')
  ))
);

const LoadingMessage = () => (
  <div>I'm loading...</div>
);

class AppProviders extends React.Component {
  constructor (props) {
    super(props);
  }

  render () {
    return <Router>
          <div>
            <ul>
              <li><Link to="/">Home</Link></li>
              <li><Link to="/bookings">Bookings</Link></li>
            </ul>
            <hr />
            <Suspense fallback={<LoadingMessage />}>
              <Switch>
                <Route exact path="/" component={HomePage} />
                <Route path="/bookings" component={BookingsPage} />
              </Switch>
            </Suspense>
          </div>
        </Router>
  }
};

export default AppProviders;

代码按预期拆分,但问题是页面 (html) 和 js 文件托管在不同的子域中,例如:

当页面加载时,它从 cdn 请求基本 js 文件:

然后 main.js 从 www.myweb.com:

请求其他块

其中 return 404.

有没有办法告诉 React lazy 从不同的子域请求文件(在这种情况下它将是 'cdn.myweb.com' 而不是 ' www.myweb.com',托管 html 页面)。

提前致谢,请原谅我的英语不好。

解决方案在webpack配置中:output.publicPath

https://webpack.js.org/configuration/output/#outputpublicpath:

This is an important option when using on-demand-loading or loading external resources like images, files, etc. If an incorrect value is specified you'll receive 404 errors while loading these resources.

同一页面中也提供了示例:

module.exports = {
  //...
  output: {
    path: path.resolve(__dirname, 'public/assets'),
    publicPath: 'https://cdn.example.com/assets/'
  }
};