VueJS Webpack模板实现懒加载:生成命名Chunk文件求助
解决Vue Webpack模板路由懒加载的Chunk命名问题
我来帮你搞定这个chunk命名的问题,其实只需要调整Webpack配置和路由懒加载的写法,就能生成setting.build.js、other1.build.js这类符合需求的命名文件。
第一步:修改Webpack生产环境配置
首先找到项目中的build/webpack.prod.conf.js文件,定位到output配置项,把chunkFilename的命名规则从[id]替换为[name]。原配置大概是这样:
output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') // 原数字命名规则 }
将chunkFilename修改为你想要的格式,比如:
chunkFilename: utils.assetsPath('js/[name].build.js')
如果需要加上hash值做缓存优化,可以写成:
chunkFilename: utils.assetsPath('js/[name].[chunkhash].build.js')
第二步:调整路由懒加载代码
这里有两种写法可选,根据你的习惯来:
写法一:沿用require.ensure风格
你原来的代码已经加了第三个参数作为chunk名,只要Webpack配置改好,这个名字就会生效。其他模块同理,替换第三个参数为对应的模块名即可:
// Setting模块 const Setting = resolve => { require.ensure(['./components/setting/Setting.vue'], () => { resolve(require('./components/setting/Setting.vue')); }, 'setting'); // 这里指定chunk名 }; // Other1模块 const Other1 = resolve => { require.ensure(['./components/other1/Other1.vue'], () => { resolve(require('./components/other1/Other1.vue')); }, 'other1'); };
写法二:使用ES动态import()(更简洁推荐)
这是目前更主流的懒加载写法,通过/* webpackChunkName: "xxx" */魔法注释指定chunk名:
// Setting模块 const Setting = () => import(/* webpackChunkName: "setting" */ './components/setting/Setting.vue'); // Other1模块 const Other1 = () => import(/* webpackChunkName: "other1" */ './components/other1/Other1.vue');
第三步:重新构建项目
修改完成后,执行npm run build,就能在dist/js目录下看到setting.build.js、other1.build.js这类符合你要求的chunk文件了。
小提示
- 确保每个模块的chunk名唯一,避免命名冲突导致chunk意外合并。
- 如果你的项目使用Webpack 4+,默认的SplitChunksPlugin会处理公共代码拆分,但不会影响你单独命名的业务模块chunk。
内容的提问来源于stack exchange,提问作者skubal
相关产品推荐
相关产品推荐

