【问题标题】:Example of setting webpack public path at runtime运行时设置 webpack 公共路径的示例
【发布时间】:2018-07-09 20:03:46
【问题描述】:

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

documentation 说:

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

像这样:

__webpack_public_path__ = myRuntimePublicPath

有人愿意创建一个 JSFiddle 示例如何做到这一点吗?

【问题讨论】:

  • 这正是你的做法。确保这是在您的应用程序中运行的第一批语句之一。
  • 比如在index.html中?

标签: javascript webpack


【解决方案1】:

将近两年后,一切都没有改变。找到一个在运行时为 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>

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

【讨论】:

  • 第一个例子对我不起作用。 codepen.io/Ni55aN/pen/QOPKVM 我在 中尝试过 __webpack_public_path__ = ..,即使 __webpack_public_path__ = window.resourceBasePath; 不起作用
  • 您知道一种将__webpack_public_path__ 重命名为其他名称以不与页面上使用Webpack 的其他组件发生冲突的方法吗?
  • 这对我有用,我需要做的是 app.js 中的window.resourceBasePath = "dynamic/path/here/"; __webpack_public_path__ = window.resourceBasePath;
猜你喜欢
  • 2022-01-02
  • 2016-09-08
  • 2017-03-26
  • 2018-07-29
  • 1970-01-01
  • 2019-11-30
  • 2016-09-02
  • 2021-05-01
  • 2023-03-24
相关资源
最近更新 更多