webpack4多頁應用HTML按需添加入口依賴chunk【html-webpack-plugin & html-inline-entry-chunk-plugin】


在webpack4中使用splitChunkPlugin時,根據需要將公共代碼拆分為多個依賴后,需要在創建htmlWebpackPlugin時候按需引入對應入口文件依賴的chunk。但是html-webpack-plugin的chunk配置項只能手動添加,在沒有得知拆分后的chunk情況下,無法得知對應html的依賴chunk,也就無法按需做引入。

因此鄙人自己寫了個配合html-webpack-plugin的插件,使用方便,效果還行,如果有幫到你,希望能在github上賜我一顆小星星。

github地址:https://github.com/pomelott/html-inline-entry-chunk-plugin

html-inline-entry-chunk-plugin使用教程如下:

單頁應用:

// webpack plugin config
    module.exports = {
        entry: {
            index: './src/js/index.js'
        },
        plugin: [
            new inlineHtmlEntryChunkPlugin(),
            // when useing inlineHtmlEntryChunkPlugin, the chunk param in htmlWebpackPlugin is invalid
            new htmlWebpackPlugin({
                entry: 'index',
                chunk: ['runtime'] //chunk is invalid
            })
        ]
    }

多頁應用:

// webpack plugin config
    module.exports = {
        entry: {
            index: './src/js/index.js',
            list: './src/js/list.js'
        },
        plugin: [
            new inlineHtmlEntryChunkPlugin(),
            new htmlWebpackPlugin({
                entry: 'index'
            }),
            new inlineHtmlEntryChunkPlugin(),
            new htmlWebpackPlugin({
                entry: 'list'
            })
        ]
    }

配置項:

Name Type Default Description
inject {Object} {css: 'head', js: 'body'} control the assets of position in HTML
tag {Object} {} Add additional resource tags
tagPriority {Number} 0 Control the insertion order of entry chunk and other tags

 

示例:

module.exports = {
        plugin: [
            new htmlInlineEntryChunkPlugin({
                inject: {
                    js: 'body',
                    css: 'head'
                },
                tagPriority: 1,
                tag: {
                    head: [
                        'https://cdn.bootcdn.net/ajax/libs/basscss/8.1.0/css/basscss-cp.css',
                        'https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js'
                    ],
                    body: [
                        'https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.0/animate.compat.css',
                        'https://cdn.bootcdn.net/ajax/libs/Chart.js/3.0.0-alpha/Chart.esm.js'
                    ]
                }
            }),
            new htmlWebpackPlugin({
                entry: 'index'
            })
        ]
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM