I am struggling to find an example of how to set the public path of an output file of a webpack bundle.
The documentation says:
If you don't know the publicPath while compiling, you can omit it and set
__webpack_public_path__
on your entry point.
Like so:
__webpack_public_path__ = myRuntimePublicPath
Would anyone be kind enough to create a JSFiddle example how this can be done?
Nothing has changed after almost two years. It's still surprisingly difficult to find an example of setting public path for webpack at runtime.
Prerequisites
For simplicity let's say our html lives in index.html
and app entry point is app.js
An example that works
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script type="application/javascript">
window.resourceBasePath = '/path/to/scripts/on/server/';
</script>
<script type="application/javascript" src="/path/to/scripts/on/server/app.js"></script>
</body>
</html>
app.js
// it is important to set global var before any imports
__webpack_public_path__ = window.resourceBasePath;
import React from 'react';
import ReactDOM from 'react-dom';
import {store, history} from './store';
const render = () => {
import('./root').then((module) => {
const Root = module.default;
ReactDOM.render(
<Root
store={store}
history={history}
/>,
document.getElementById('app'),
);
});
};
render();
if (module.hot) {
module.hot.accept('./root', render);
}
An example that doesn't work
Webpack publicPath documentation says it's enough just to set a global variable with the right name. I did that:
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script type="application/javascript">
__webpack_public_path__ = '/path/to/scripts/on/server/';
</script>
<script type="application/javascript" src="/path/to/scripts/on/server/app.js"></script>
</body>
</html>
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import {store, history} from './store';
const render = () => {
import('./root').then((module) => {
const Root = module.default;
ReactDOM.render(
<Root
store={store}
history={history}
/>,
document.getElementById('app'),
);
});
};
render();
if (module.hot) {
module.hot.accept('./root', render);
}
In this case my app fails complaining in console it couldn't load 0.js
from current path to index.html
. Which means that setting public path didn't have any impact.
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