I love the ability to dynamically import a chunk using the import
command in webpack 3. Unfortunately it seems as if it can only be used if the resources are in a rather static directory configuration on the server.
In my environment the html pages generated dynamically in the backend (let's say http:/localhost/app
). All other resources (js, css, images, etc.) are in a different directory (let's say http:/localhost/res
) but additionally res
is not static but can rather change dynamically in the backend.
As long as I do not use any dynamic imports everything works as expected but when trying to dynamically load any chunks this fails because webpack by default expects the chunks to be in http:/localhost/app
and I cannot use publicPath
because the url where the resources are is dynamic.
Is there any way to (runtime) configure webpack into loading the resources relative to the path where the current resource is located.
If for example the chunk page1.js
located in http:/localhost/resA
dynamically loads the chunk sub1.js
he should look for it in http:/localhost/resA
instead of http:/localhost/app
.
generated html will be available at http:/localhost/app/page1
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="http:/localhost/resA/page1.bundle.js"></script>
</body>
</html>
file src/page1.js
will be available as http:/localhost/resA/page1.bundle.js
:
import(/* webpackChunkName: "sub1" */ './sub1').then(({MyClass}) => {/*...*/});
file src/sub1
will be available as http:/localhost/resA/sub1.bundle.js
:
export class MyClass {};
file `webpack.config.js':
const path = require('path');
const webpack = require('webpack');
function config(env) {
return {
entry: {
index: ['./src/page1.js']
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: './'
},
module: {
rules: [
{
test: /\.js$/i,
include: /src/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
devtool: 'source-map'
};
}
module.exports = config;
The solution is to use __webpack_public_path__
as described in https://webpack.js.org/guides/public-path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With