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

CLJ*_*CLJ 5 javascript webpack

我正在努力寻找一个示例,说明如何设置Webpack捆绑包输出文件的公共路径。

文件说:

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

像这样:

__webpack_public_path__ = myRuntimePublicPath
Run Code Online (Sandbox Code Playgroud)

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

小智 9

将近两年后,一切都没有改变。找到一个在运行时为 webpack 设置公共路径的例子仍然非常困难。

先决条件

  • 网络包 4.5.0
  • 一个足够大的应用程序来利用代码拆分

为简单起见,假设我们的 html 存在于其中index.html,应用程序入口点是app.js

一个有效的例子

索引.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>
Run Code Online (Sandbox Code Playgroud)

应用程序.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);
}
Run Code Online (Sandbox Code Playgroud)

一个不起作用的例子

Webpack publicPath 文档说只要设置一个具有正确名称的全局变量就足够了。我是这样做的:

索引.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>
Run Code Online (Sandbox Code Playgroud)

应用程序.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);
}
Run Code Online (Sandbox Code Playgroud)

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