推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
Xheldon

Webpack 动态设置 __webpack_public_path__ 到底怎么用

  •  1
     
  •   Xheldon · Sep 14, 2018 · 9353 views
    This topic created in 2979 days ago, the information mentioned may be changed or developed.

    看了中文英文文档, 说的是可以替代 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 replies  •  2019-12-11 01:15:43 +08:00
    readonly
    readonly
    Sep 15, 2018 via iPhone
    1
    感觉是 import 语法自动提升了
    Xheldon
    Xheldon
    OP
    Sep 17, 2018
    2
    @readonly 没, 试了下, 跟语法提升没关系 =_=
    surgit
    surgit
    Nov 21, 2018
    3
    publicPath 要删掉,不能为空字符串 ''
    changfenglu
    changfenglu
    Dec 1, 2018
    4
    htmlwebpackplugin 不支持__webpack_public_path__变量,可以使用 webpack-html-independent-public-path 这个插件给 htmlwebpackplugin 插件指定单独的 publicPath 处理
    geekdonie
    geekdonie
    Dec 11, 2019
    5
    官方文档: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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1016 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 19:09 · PVG 03:09 · LAX 11:09 · JFK 14:09
    ♥ Do have faith in what you're doing.