You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack多入口数组配置为何仅打包最后一个文件?

Webpack数组式Entry仅打包最后一个文件的原因分析

问题场景

目录结构

src
|---index1.js
|---index2.js
package.json
webpack.config.js

代码内容

src/index1.js:

export function Func1() {
    return 1111;
}

src/index2.js:

export function Func2() {
    return 2222;
}

webpack.config.js:

const path = require('path');

module.exports = {
  entry: ['./src/index2.js', './src/index1.js'],
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

异常现象

打包生成的main.js仅包含Func1的代码,Func2完全缺失。根据Webpack官方文档描述:

We can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry". This is useful when you would like to inject multiple dependent files together and graph their dependencies into one "chunk".

原本预期Webpack会将两个入口文件都打包进产物,实际却只保留了最后一个文件的内容。

核心原因

问题出在Webpack的**Tree Shaking(摇树优化)**机制上:

  • Webpack 4+ 默认在生产模式下启用Tree Shaking,它会扫描代码中的导出内容,若未被任何地方引用,就会将这部分“死代码”从最终产物中移除。
  • 你的两个入口文件仅定义并导出了函数,既没有在模块内部执行代码,也没有被其他模块引用。对于数组式entry,Webpack会按顺序加载所有入口模块,但如果模块没有副作用(即没有执行任何会影响外部环境的代码,仅导出),且导出内容未被使用,就会被Tree Shaking剔除。
  • 最后一个文件的Func1被保留,是因为Webpack在处理数组式entry时,会默认将最后一个模块的导出作为chunk的对外导出结果,即使没有被使用,也会被保留;而前面的index2.js因无引用、无副作用,被彻底移除。

解决方法

方法1:标记模块有副作用

在package.json中添加sideEffects字段,告诉Webpack这些模块不能被Tree Shaking移除:

{
  "sideEffects": ["./src/index1.js", "./src/index2.js"]
}

如果所有源码文件都需要保留副作用,也可以直接设置为true:

{
  "sideEffects": true
}

方法2:主动引用或使用导出内容

修改入口模块,主动引用另一个文件的导出,或者执行相关代码,让Webpack认为该模块有使用价值:

// 修改src/index1.js
export function Func1() {
    return 1111;
}
// 引用并使用index2的导出
import { Func2 } from './index2.js';
// 哪怕只是无意义的调用,也能阻止Tree Shaking
Func2();

方法3:改用多入口对象配置

如果需要两个文件的内容都被打包且独立,可以将entry配置为对象形式,生成多个chunk:

// 修改webpack.config.js
const path = require('path');

module.exports = {
  entry: {
    index1: './src/index1.js',
    index2: './src/index2.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
};

打包后会生成index1.js和index2.js两个文件,各自包含对应模块的代码。


内容的提问来源于stack exchange,提问作者timewalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:52:44