我很难找到如何设置webpack捆绑包输出文件的公共路径的示例。
文档说:
如果在编译时不知道publicPath,可以省略它并在入口点上设置
__webpack_public_path__
。
就像这样:
__webpack_public_path__ = myRuntimePublicPath
有没有人可以好心创建一个JSFiddle示例来展示如何完成这个操作?
我很难找到如何设置webpack捆绑包输出文件的公共路径的示例。
文档说:
如果在编译时不知道publicPath,可以省略它并在入口点上设置
__webpack_public_path__
。
就像这样:
__webpack_public_path__ = myRuntimePublicPath
有没有人可以好心创建一个JSFiddle示例来展示如何完成这个操作?
近两年来,没有任何变化。令人惊讶的是,在运行时设置webpack公共路径的示例仍然很难找到。
先决条件
为了简单起见,假设我们的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中。这意味着设置公共路径没有任何影响。
__webpack_public_path__ = ..
,
甚至
__webpack_public_path__ = window.resourceBasePath;
也不起作用。 - Ni55aN__webpack_public_path__
重命名为其他名称,以避免与页面上使用 Webpack 的其他组件发生冲突吗? - Shlomiwindow.resourceBasePath = "dynamic/path/here/"; __webpack_public_path__ = window.resourceBasePath;
在 app.js 中。 - Low