Webpack 动态设置 __webpack_public_path__ 到底怎么用

2018-09-14 19:34:46 +08:00
 Xheldon

看了中文英文文档, 说的是可以替代 output.publicPath, 需要将 output.publicPath 设置成'', 然后在入口文件设置 __webpack_public_path__ = 'http:///a.com'; 就行了;

预期结果是 htmlwebpackplugin 打包后的 html 文件中的 js 引入地址是 'http"//a.com/xx.js'

我是这么做的:

webpack.config.js 这么设置:

output: {
	filename: '[name].[hash:8].js',
	publicPath: ''
}

htmlwebpackplugin 插件这么设置:

let entries = glob.sync('./src/entries/**/index.js').reduce((prev, curr) => {
    prev['assets/' + curr.slice(14, -3)] = curr;
    return prev;
}, {}); // entries 同时是 webpack 的 entry js

let htmls = Object.keys(entries).map((html) => {
    return new HWP({
        title: html.slice(-5, -1), // 这些个不重要, 不要在意
        filename: `${html.slice(7, -6)}.html`, // 这些个不重要, 不要在意
        template: './src/tpl/index.html', 
        chunks: [html], // 这些个不重要, 不要在意
        inject: 'body', // 这些个不重要, 不要在意
        minify: false,
        data: {
            build: true
        }
    });
});

入口文件这么设置:

    __webpack_public_path__ = 'http://a.com';
    
    import a from './a.js';
    import b from './b.js';
    blabla...

然后满心欢喜的期待生成的 html 中的 script 中的 src 属性是 http://a.com/**/*.js 但是并没有带上 http://a.com

翻看了 SO, github, 都说这样就 OK 了, 但是我没有得到预期结果 是我遗漏了什么, 还是我对这个 __webpack_public_path__ 理解有误?

7798 次点击
所在节点    JavaScript
5 条回复
readonly
2018-09-15 00:18:09 +08:00
感觉是 import 语法自动提升了
Xheldon
2018-09-17 13:49:38 +08:00
@readonly 没, 试了下, 跟语法提升没关系 =_=
surgit
2018-11-21 20:43:55 +08:00
publicPath 要删掉,不能为空字符串 ''
changfenglu
2018-12-01 15:43:31 +08:00
htmlwebpackplugin 不支持__webpack_public_path__变量,可以使用 webpack-html-independent-public-path 这个插件给 htmlwebpackplugin 插件指定单独的 publicPath 处理
geekdonie
2019-12-11 01:15:43 +08:00
官方文档:Be aware that if you use ES6 module imports in your entry file the __webpack_public_path__ assignment will be done after the imports. In such cases, you'll have to move the public path assignment to its own dedicated module and then import it on top of your entry.js

https://webpack.js.org/guides/public-path/#on-the-fly

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/489456

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX