如何在 webpack 的 require.ensure 回调中操作对 chunk js 文件的请求 url?

How to manipulate the request url for chunk js file inside require.ensure callback of webpack?

随着web开发的进行,js bundle文件越来越大,导致网页初始渲染的延迟很大。最近在研究webpack,里面用require.ensure做懒加载,很神奇。但是我遇到了我的特定情况的问题。

说明如下: 当我捆绑我的 js 文件时,它会生成两个块: ./bundle/bundle.js ./bundle/1.js (which is for lazy lodaing)

但是,我想在不同的页面中延迟加载1.js。但是在不同的页面上对它的请求是不同的。

例如。如果在 page1 上,它正在请求 http://localhost/page1/1.js.
在 page2 上,它正在请求 http://localhost/page2/1.js.

这给后端带来了一个问题,它不知道如何向它提供文件。所以真的想知道如何解决它?有没有办法在 require.ensure 回调函数中操纵请求 url,以便无论页面在哪里,它都使用相同的 url 请求?

您必须在您的 webpack 配置中使用 publicPath 参数 - 这正是您想要的:

output: {
    ...
    publicPath: '/scripts/' // Path to scripts relative to your site root
}