Search code examples
javascriptwebpackwebpack-4dynamic-loading

Webpack: output.path, publicPath and chunkFilename selecting concept for projects where html and js files are not in the same folder


From the webpack documentation for output.publicPath:

Simple rule: The URL of your output.path from the view of the HTML page.

module.exports = { 
  output: {
    path: path.resolve(__dirname, 'public/assets'),
    publicPath: 'https://cdn.example.com/assets/'   
  } 
}; 

Above rule is actual for single-page applications, where usually index.html and index.js are in the same folder. However, in the projects of multi page websites, usually special folder like js or scripts is being created. So the file structure of output folder of project could be like:

enter image description here

I tried a lot of combinations of output.path output.publicPath and output.chunkFilename, however still do not understand, how to correctly select the combination of above parameters to make dynamic load works (e. g. const MODULE = import('./loadOnDemand/testModule') which is chunks/chunk__0.js in output folder). Please tell me the concept, how to select output.path publicPath and chunkFilename, which will works for above file system, and also could be scaled on below file system:

enter image description here


Solution

  • Have you tried webpack magic comments to automatically target the chunk names? https://medium.com/faceyspacey/how-to-use-webpacks-new-magic-comment-feature-with-react-universal-component-ssr-a38fd3e296a

    const MODULE = import(/* webpackChunkName: 'test' */'./loadOnDemand/testModule')