Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of setting webpack public path at runtime

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?

like image 256
CLJ Avatar asked Oct 05 '16 16:10

CLJ


1 Answers

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

  • webpack 4.5.0
  • an app big enough to leverage code splitting

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.

like image 166
sergio Avatar answered Nov 03 '22 10:11

sergio