Webpack3+React16代码分割的实现(2)

function readFileList(dir, filesList = []) { const files = fs.readdirSync(dir) files.forEach((item) => { let fullPath = path.join(dir, item) const stat = fs.statSync(fullPath) if (stat.isDirectory()) { // 递归读取所有文件 readFileList(path.join(dir, item), filesList) } else { /\.js$/.test(fullPath) && filesList.push(fullPath) } }) return filesList } exports.commonPaths = readFileList(path.join(__dirname, '../src/components'), [])

webpack配置抽离common

import conf from '**'; module.exports = { entry: { common: conf.commonPaths, index: ['babel-polyfill', `./${conf.index}`], }, ... //其他配置 plugins:[ new webpack.optimize.CommonsChunkPlugin('common'), ... // other plugins ] }

在webpack3中使用CommonsChunkPlugin来提取第三方库和公共模块,传入的参数 common 是entrty已经存在的chunk, 那么就会把公共模块代码合并到这个chunk上。

提取common后的代码

将各个路由重复的代码提取出来后,包的总大小又变为了2.5M。多出了一个common的bundle文件。(common过大,其实还可以继续拆分)

Webpack3+React16代码分割的实现

总结

webpack打包还有很多可以优化的地方,另外不同webpack版本之间也有点差异,拆包思路就是提取公共,根据使用场景按需加载。

到此这篇关于Webpack3+React16代码分割的实现的文章就介绍到这了,更多相关Webpack3+React16代码分割内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsgxpg.html