如何配置 webpack 的自动代码拆分以加载相对于构建输出文件夹的模块?

How can I configure webpack's automatic code splitting to load modules relative to the build output folder?

我正在使用 Webpack 2 的自动代码拆分将我的应用程序分成多个输出文件。我的 webpack.config.js 文件是:

const path = require('path');

module.exports = {
  entry: './app.js',
  output: {
    filename: '[name].js',
    path: path.join(__dirname, 'build'),
  }
}

这会正确地将我的 app.js 文件与其他模块文件一起构建到 build 文件夹中。构建目录包含以下文件:

main.js
0.js

我的问题是,当 main.js 请求 0.js 时,它是在我的应用程序的根目录下执行的,而不是相对于其当前位置。所以它基本上是在应该加载 localhost:8000/build/0.js 时尝试加载 localhost:8000/0.js。如何配置我的项目,以便我的项目正确加载相对于我的主入口点路径的拆分模块?

默认情况下,Webpack 将从根目录加载模块。您可以通过在入口点声明 __webpack_public_path__ 变量来配置 Webpack 将从哪个文件夹加载。因此,对于这种情况,您可以使用:

__webpack_public_path__ = 'build/';

Webpack 然后将从 build 文件夹加载模块。然而,这仍然是相对于根而言的。为了告诉 Webpack 加载相对于入口点的脚本,您可以动态配置 __webpack_public_path__ 到入口点脚本的目录:

const scriptURL = document.currentScript.src;
__webpack_public_path__ = scriptURL.slice(0, scriptURL.lastIndexOf('/') + 1);

document.currentScriptwell supported in evergreen browsers,但在 Internet Explorer 中不受支持。