Open nitroge opened 3 years ago
import _ from 'lodash'; console.log(_.join(['a', 'b', 'c'])); // 此处省略1w行业务代码
打包后:dist/main.js->2mb
lodash不会改变,而业务逻辑经常发生改变 打包文件很大,加载时间很长 业务逻辑发生变化时,用户又要加载2mb的内容 解决方案: 1.自己手动分割 ./src/lodash.js import _ from 'lodash'; window._ = _; ./src/index.js console.log(_.join(['a', 'b', 'c'])) 打包后:dist/main.js->1mb,dist/vendors-....js->1mb 2.webpack插件-splitChunks module.export = { optimization: { splitChunks: { chunks: 'all', }, }, } 打包后:dist/main.js->1mb,dist/vendors-....js->1mb 总结 Code splitting本质和webpack无关系,这是一种思想,通过合理的代码分割,让项目运行的性能更高 同步代码:在webpack.config.js中进行optimization的配置 异步代码(import):无需做任何配置,会自动进行代码分割
import _ from 'lodash'; window._ = _;
console.log(_.join(['a', 'b', 'c']))
打包后:dist/main.js->1mb,dist/vendors-....js->1mb
module.export = { optimization: { splitChunks: { chunks: 'all', }, }, }
为什么需要进行代码分割?
./src/index.js
打包后:dist/main.js->2mb