gpt4 book ai didi

reactjs - 从 CDN react 延迟导入

转载 作者:行者123 更新时间:2023-12-03 14:11:55 24 4
gpt4 key购买 nike

我正在按照本指南使用 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文件托管在不同的子域中,例如:

  • 页面:http://www.myweb.com/
  • js 文件:http://cdn.myweb.com/

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

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

但是 main.js 从 www.myweb.com 请求其他 block :

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

返回 404。

有没有办法告诉 React 懒惰地从不同的子域请求文件(在本例中,它将是“cdn.myweb.com”而不是“www.myweb.com”)。 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/'
}
};

关于reactjs - 从 CDN react 延迟导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54538243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com