Webpack5 中如何修改入口节点,实现代码分离

59

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第24天,点击查看活动详情

修改入口节点,实现代码分离

这种方式是迄今为止最简单直观的分离代码的方法。不过,这种方式手动配置较多,并有一些隐患,我们将会解决这些问题。

在项目的 src 目录下新建 another-module.js 文件,在这个文件中加载第三方模块 lodash,并且使用 lodash 中 join() 方法拼接字符串:

import Lodash from 'lodash';
console.log(Lodash.join(['Another', 'module', 'loaded!'], '-'));

修改 webpack.config.js 配置文件,将 another-module.js 添加到 entry 模块中,之前使用 entry 只是配置一个入口,现在需要将其配置成对象。

// webpack.config.js
//...
module.exports = {
  //entry: './src/index.js',
  entry:{


    index: './src/index.js',
    another: './src/another-module.js'
  },
//...
}

编译打包,发现打包失败,失败的原因是多个入口文件打包生成同一个同名的 bundle.js 文件。因此,我们需要分别对两个入口的文件起不同的输出文件名。

image.png

修改 webpack.config.js 配置文件中 output 模块配置,配置 output.filename 选项的直为 [name].bundle.js,使用 [name] 方法获取 entry 入口文件 chunk 的 key 1名字。

// webpack.config.js
//...
module.exports = {
  //...
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, './dist'),
    clean: true,
    assetModuleFilename: 'images/[contenthash][ext]'
  },
//...
}

执行 npx webpack 编译,可以看到 dist 目录下生成 index.bundle.js 和 another.bundle.js 这两个文件,并且 another.bundle.js 文件大小为 1.38M,原因是我们在 another-module.js 文件中引入 lodash 库,并将其打包输出到该该文件中。

image.png

同时,在 index_app.html 文件中,通过

<script defer src="index.bundle.js"></script>
<script defer src="another.bundle.js"></script>

启动服务,在浏览器访问:http://localhost:8080/index_app.html,控制台输出如下效果。

image.png   现在,加入我们需要在其他模块中引入 lodash 库。  

// src/index.js
import Lodash from 'lodash';
console.log(Lodash.join(['Index', 'module', 'loaded!'], '-'));

执行 npx webpack 打包,发现 index.bundle.js 文件大小由原来 24.2kb 变为 1.4M,说明在 index.js 引入的 lodash 也被打包到 index.bundle.js 文件中。

image.png

lodash 是共享的一个公共的模块,但是如果我们使用这种多入口的方法,它分别的把各自引用的,通用的这样的方式都分别打到各自的 chunk 里。其实,这也是我们 entry 配置代码分离的一个问题。

总结一下,这种方式存在一些隐患:

  • 如果我们在入口的 chunk 之间包含一些重复的代码,比如使用 lodash 库,那么这些重复的模块会被引入到各自的 bundle 中。

  • 这种方法不够灵活,并且不能动态地将核心应用程序逻辑中的代码拆分出来。

如何解决代码打包重复问题呢?