I'm following this guide to lazy load using React Router and Suspense:
https://itnext.io/async-react-using-react-router-suspense-a86ade1176dc
and this is the code I have so far:
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;
Code is splitted as expected, but the problem is that the page (html) and the js files are hosted in different subdomains, for example:
When page loads it requests the base js file from the cdn:
but then main.js requests the other chunks from www.myweb.com:
which return 404.
Is there a way to tell React lazy to request the files from a different subdomain (in this case it would be 'cdn.myweb.com' instead of 'www.myweb.com', where html page is hosted).
May thanks in advance and excuse me for my bad English.
The solution is in webpack configuration: 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.
An example is provided in the same page, too:
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'public/assets'),
publicPath: 'https://cdn.example.com/assets/'
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With