怎么提取html公共代码,webpack-html-plugin不自动引用splitChunks提取的公共代码?

本文讨论了在使用Webpack的splitChunks功能时,如何确保被提取的公共模块(如vendor)在每个单独的HTML页面中自动引入的问题。作者分享了遇到的困惑,并提出了关于如何避免手动配置每个HTML模板中chunks属性的建议,寻求最佳实践以简化打包过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先贴上项目结构,bVbg2Ic?w=237&h=761

webpack.base.config.js部分代码

// 配置常量

const SRC_PATH = path.resolve(__dirname, ‘../src’);

const OUTPUT_PATH = path.resolve(__dirname, ‘../dist’);

const PUBLIC_PATH = ‘/dist/’;

// 获取html-webpack-plugin参数的方法

const getHtmlConfig = function(name){

return {

template    : './views/' + name + '.html',

filename    : name + '.html',

title       : name,

inject      : true,

hash        : true,

chunks      : [name,'common']

};

};

const config = {

context: SRC_PATH,

entry: {

common : ['./pages/common/index.js'],

index: ['./pages/index/index.js'],

about: ['./pages/about/index.js'],

user: ['./pages/user/index.js']

},

output: {

path: OUTPUT_PATH,

filename: 'js/[name].[chunkhash:6].js',

publicPath: PUBLIC_PATH

},

resolve : {

alias : {

$src : path.resolve(__dirname,'../src')

}

},

plugins: [

new htmlWebpackPlugin(getHtmlConfig('index')),

new htmlWebpackPlugin(getHtmlConfig('about')),

new htmlWebpackPlugin(getHtmlConfig('user'))

]

}

webpack.prod.config.js 部分代码如下

const config = merge(baseConfig,{

mode : 'production',

optimization : {

splitChunks : {

cacheGroups : {

commons : {

name : 'vendor',

minChunks : 2,

chunks : 'all'

}

}

}

}

})

在入口文件index、about和user中都引入了lodash,最后打包出来如图

bVbg2Hy?w=692&h=243

此时由于splitChunks将公共模块提取出来为vendor,但是打开最后打包生成的三个html文件(index,about,user)发现只引入了当时配的 chunks : [name,’common’] ,而vendor并没有自动引入,我觉得这里不应该把vendor写入到webpackHtmlPlugin的chunks项里面吧,因为假设我index引入了一个模块,我的user也引入了一个模块,但是我可能忘了或者并不清楚两个模块是相同的,但是splitChunks提取出来了,我也不可能所有的webpackHtmlPlugin的chunks项都引入,那就没意义了呀,请问被splitChunks提取的公共模块有没有办法自动引入呢?谢谢

950-390_%E7%94%BB%E6%9D%BF-1.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值