在webpack配置中,配置的splitChunks , 将代码进行分割 。

    分为单入口 和 双入口 场景

    实例 :

    1. //1. 单入口文件,
    2. module.exports = {
    3. entry: './src/index.js',
    4. // webpack 配置性能优化的配置
    5. optimization: {
    6. // 代码分割配置
    7. splitChunks: {
    8. chunks: 'all'
    9. }
    10. }
    11. }
    12. // 2. 多入口文件
    13. module.exports = {
    14. entry: {
    15. index: './src/index.js',
    16. test: './src/test.js'
    17. },
    18. // webpack 配置性能优化的配置
    19. optimization: {
    20. // 代码分割
    21. splitChunks: {
    22. chunks: 'all'
    23. }
    24. }
    25. }

    如果 entry 只有一个入口文件, 打包会生成一个 chunk 入口, 如果 entry 有两个入口文件, 打包生成 两个 chunk 入口

    配置 splitChunks 目的:

    1. 如果入口文件中引入了下载的包文件,可以将 node_modules 中代码单独打包成一个 chunk 最终输出
    2. 自动分析多入口的 chunk 中, 有没有公共的文件。 如果有会单独打包成一个 chunk

    代码分割优点:

    • 不会重复打包多次