运行时设置Webpack公共路径的示例

14

我很难找到如何设置webpack捆绑包输出文件的公共路径的示例。

文档说:

如果在编译时不知道publicPath,可以省略它并在入口点上设置__webpack_public_path__

就像这样:

__webpack_public_path__ = myRuntimePublicPath

有没有人可以好心创建一个JSFiddle示例来展示如何完成这个操作?


这就是你该怎么做。确保这是你的应用程序中要运行的第一条语句之一。 - Mario Tacke
例如在index.html中? - vlio20
1个回答

14

近两年来,没有任何变化。令人惊讶的是,在运行时设置webpack公共路径的示例仍然很难找到。

先决条件

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

为了简单起见,假设我们的HTML文件位于index.html,应用程序入口点位于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>

应用程序的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文档说只需设置一个名字正确的全局变量即可。我也这样做了:

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>

应用程序.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。这意味着设置公共路径没有任何影响。

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


第一个例子对我不起作用。 https://codepen.io/Ni55aN/pen/QOPKVM我已经在<head>中尝试了__webpack_public_path__ = .., 甚至 __webpack_public_path__ = window.resourceBasePath;也不起作用。 - Ni55aN
你知道如何将 __webpack_public_path__ 重命名为其他名称,以避免与页面上使用 Webpack 的其他组件发生冲突吗? - Shlomi
这对我有用,我所需要做的就是 window.resourceBasePath = "dynamic/path/here/"; __webpack_public_path__ = window.resourceBasePath; 在 app.js 中。 - Low

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接