Search code examples
javascriptwebpackwebpack-2

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


I'm using Webpack 2's automatic code splitting to divide up my application into multiple output files. My webpack.config.js file is:

const path = require('path');

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

This correctly builds my app.js file into the build folder along with the other module files. The build directory has the following files:

main.js
0.js

My issue is that when main.js requests 0.js, it does so at the root of my application, rather than relative to its current location. So it's basically trying to load localhost:8000/0.js when it should be loading localhost:8000/build/0.js. How can I configure my project so that my project correctly loads split modules relative to my main entry point's path?


Solution

  • By default Webpack will load modules from the root directory. You can configure what folder Webpack will load from by declaring the __webpack_public_path__ variable in your entry point. So, for this scenario, you could use:

    __webpack_public_path__ = 'build/';
    

    Webpack will then load modules from the build folder. However this is still relative to the root. In order to tell Webpack to load scripts relative to the entry point, you can dynamically configure __webpack_public_path__ to the directory of your entry point script with:

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

    document.currentScript is well supported in evergreen browsers, but is not supported in Internet Explorer.