javascript – 在运行时设置webpack公共路径的示例

我正在努力寻找一个如何设置webpack包的输出文件的公共路径的示例.

documentation说:

If you don’t know the publicPath while compiling, you can omit it and
set __webpack_public_path__ on your entry point.

像这样:

__webpack_public_path__ = myRuntimePublicPath

有人会非常友好地创建一个JSFiddle示例如何做到这一点?

最佳答案 近两年后没有任何改变.在运行时找到为webpack设置公共路径的示例仍然令人惊讶地困难.

先决条件

> webpack 4.5.0
>一个足以利用代码拆分的应用程序

为简单起见,假设我们的html位于index.html,app入口点为app.js

一个有效的例子

的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);
}

一个不起作用的例子

Webpack publicPath documentation说仅仅设置一个具有正确名称的全局变量就足够了.我这样做了:

的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);
}

在这种情况下,我的应用程序无法在控制台中抱怨它无法将当前路径中的0.js加载到index.html.这意味着设置公共路径没有任何影响.

点赞