我有一些延迟导入的 React 组件 App.tsx
. App.tsx
用于Index.tsx
它被渲染并附加到 body
.
const IndexPage = lazy(() => import("../features//IndexPage"));
const TagsPage = lazy(
() => import("../features/tags/TagsPage")
);
const ArticlePage = lazy(() => import("../features/article/ArticlePage"));
const SearchResultPage = lazy(
() => import("../features/search-result/SearchResultPage")
);
const ErrorPage = lazy(() => import("../features/error/ErrorPage"));
----
<BrowserRouter basename={basename}>
<Suspense fallback={<Fallback />}>
<Routes>
<Route path={INDEX} element={<IndexPage />} />
<Route path={ARTICLE} element={<ArticlePage />} />
<Route path={TAGS} element={<TagsPage />} />
<Route path={SEARCH} element={<SearchResultPage />} />
<Route path={ERROR} element={<ErrorPage />} />
<Route path="/*" element={<ErrorPage />} />
</Routes>
</Suspense>
</BrowserRouter>
通常,在生产中会发生以下错误。无法获取动态导入的模块:
它发生在所有路线上。
https://help.example.io/static/js/SearchResultPage-c1900fe3.js
https://help.example.io/static/js/TagsPage-fb64584c.js
https://help.example.io/static/js/ArticlePage-ea64584c.js
https://help.example.io/static/js/IndexPage-fbd64584c.js
我已经更改了构建路径。因此,它是 /static/js
. build: {
assetsInlineLimit: 0,
minify: true,
rollupOptions: {
output: {
assetFileNames: (assetInfo) => {
var info = assetInfo.name.split(".");
var extType = info[info.length - 1];
if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(extType)) {
extType = "img";
} else if (/woff|woff2/.test(extType)) {
extType = "css";
}
return `static/${extType}/[name]-[hash][extname]`;
},
chunkFileNames: "static/js/[name]-[hash].js",
entryFileNames: "static/js/[name]-[hash].js",
},
},
outDir: "./../backend/src/main/resources/static/articles/",
emptyOutDir: true,
},
有人知道如何解决这个问题吗?更新:
我在开发中从未遇到过这个错误。我用 哨兵跟踪错误。这在两个月内至少发生了 274 次。
这就是 Sentry 上的全部内容。
{
arguments: [
{
message: Failed to fetch dynamically imported module: https://help.example.io/static/js/SearchResultPage-c1900fe3.js,
name: TypeError,
stack: TypeError: Failed to fetch dynamically imported module: https://help.example.io/static/js/SearchResultPage-c1900fe3.js
}
],
logger: console
}
更新在过去的两个月里,我们有 500000 次访问。它发生了 274 次。由于
tracesSampleRate
是 0.3
,肯定不止于此。 Sentry.init({
dsn: "",
integrations: [new BrowserTracing()],
tracesSampleRate: 0.3,
});
它发生在各种浏览器上,但主要发生在 Chrome 上。我无法在 dev 或 prod 中重现它。
最佳答案
如果没有所有数据,很难直接回答这个问题,但我会尽力做到最好,并分享一些相关的资源。
正如评论中所讨论的,可能有 许多 发生这种情况的原因。由于您无法重现,而且它不是恒定的,我们可能可以排除它来自您的代码或部署配置的理论。
我头顶有几个原因:
我相信这个错误类似于“ChunkLoadError”(在许多其他框架中也遇到过,不仅仅是 React),附上一个类似的问题:Webpack code splitting: ChunkLoadError - Loading chunk X failed, but the chunk exists ,请注意相同数量的流量失败等。
尝试解决此问题, try catch 错误并强制重新加载以重新获取资源,但请确保不要在那里循环。
https://medium.com/@botfather/react-loading-chunk-failed-error-88d0bb75b406
我希望这有帮助。
关于javascript - 获取动态导入模块失败 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72376333/