Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React lazy import from cdn

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:

  • page: http://www.myweb.com/
  • js files: http://cdn.myweb.com/

When page loads it requests the base js file from the cdn:

  • http://cdn.myweb.com/js/main.js

but then main.js requests the other chunks from www.myweb.com:

  • http://www.myweb.com/js/1.js
  • http://www.myweb.com/js/2.js

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.

like image 584
Fernando Avatar asked Oct 21 '25 05:10

Fernando


1 Answers

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/'
  }
};
like image 83
Fernando Avatar answered Oct 23 '25 22:10

Fernando