V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
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 · 8816 views
    This topic created in 2787 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
        1
    readonly  
       Sep 15, 2018 via iPhone
    感觉是 import 语法自动提升了
    Xheldon
        2
    Xheldon  
    OP
       Sep 17, 2018
    @readonly 没, 试了下, 跟语法提升没关系 =_=
    surgit
        3
    surgit  
       Nov 21, 2018
    publicPath 要删掉,不能为空字符串 ''
    changfenglu
        4
    changfenglu  
       Dec 1, 2018
    htmlwebpackplugin 不支持__webpack_public_path__变量,可以使用 webpack-html-independent-public-path 这个插件给 htmlwebpackplugin 插件指定单独的 publicPath 处理
    geekdonie
        5
    geekdonie  
       Dec 11, 2019
    官方文档: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   ·   Solana   ·   2128 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 00:33 · PVG 08:33 · LAX 17:33 · JFK 20:33
    ♥ Do have faith in what you're doing.