所以 Webpack 动态设置 __webpack_public_path__ 到底怎么用?

看了中文英文文档, 说的是可以替代 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 理解有误?

阅读 5.1k
1 个回答

publicPath 删掉,不能为空字符串

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题