如何让 Webpack 支持从 src/components/Button/index.tsx 自动查找文件?

解读

面试官真正想考察的是“你是否理解 Webpack 的模块解析规则,以及能否在不改业务代码的前提下,让 import Button from '@/components/Button' 这种写法直接定位到 src/components/Button/index.tsx”。
国内项目普遍用 TypeScript + React,目录约定“一个文件夹一个组件,入口文件叫 index.tsx”。如果每次都要写全路径 import Button from '@/components/Button/index.tsx',既啰嗦又容易出错。
因此,考点集中在三点:

  1. 如何告诉 Webpack “.tsx 是合法后缀,可以省略”;
  2. 如何告诉 Webpack “遇到文件夹先找 index.tsx”;
  3. 如何用别名把冗长的相对路径变成语义化的绝对路径(如 @)。
    答出这三层,才算“工程化思维”到位。

知识点

  1. resolve.extensions:配置 Webpack 自动补全的后缀列表;顺序影响性能,高频在前。
  2. resolve.mainFiles:配置文件夹的默认入口文件名,默认是 ["index"],需要把 "index.tsx" 提到最前。
  3. resolve.alias:把长路径映射成短别名,避免 ../../../../ 地狱;国内习惯用 @ 代表 src。
  4. tsconfig.json 的 paths 与 baseUrl:仅给 IDE 和 tsc 提示,Webpack 不感知,必须配合 tsconfig-paths-webpack-plugin 或同步配置 alias,否则编译阶段会“跳红”。
  5. 性能注意:extensions 数组过长或 mainFiles 顺序不合理,会导致 Webpack 多次 IO 试错,CI 构建时长增加;国内大厂常规做法是后缀数组 ≤ 6 项,mainFiles 仅保留 ["index.tsx", "index.ts", "index"]。

答案

分三步配置即可,无需改动任何业务代码:

  1. 配置别名(避免相对路径地狱)
// webpack.config.js
const path = require('path');
module.exports = {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    },
    extensions: ['.tsx', '.ts', '.jsx', '.js'],
    mainFiles: ['index.tsx', 'index.ts', 'index']
  }
};
  1. 同步 TypeScript 提示(防止 VSCode 报错)
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
  1. 验证
    目录结构
src
└─ components
   └─ Button
      ├─ index.tsx
      └─ style.module.less

业务代码里直接写

import Button from '@/components/Button';

Webpack 会按以下顺序查找:
src/components/Button/index.tsx → 命中,完成打包;
若不存在则降级找 index.ts → index.jsx → index.js,均不存在才抛 Module not found。
至此,自动查找目标达成。

拓展思考

  1. 微前端场景:如果 Button 是 npm 包 @company/react-ui,但本地开发想“链路级联”到源码,可用 resolve.alias 把 @company/react-ui 指向本地 src/components/Button,实现“零链路调试”,国内阿里、字节等团队常用。
  2. 严格区分“构建时”与“运行时”:以上配置只影响 Webpack 的静态分析,不会改变服务器路由或 Node 端解析;做 SSR 时,服务器入口仍需 ts-node 配合相同的 paths 映射,否则同一份代码在服务端会 Cannot find module。
  3. 大型 monorepo:pnpm workspace 里子包交叉引用,推荐用 resolve.modules = ['node_modules', '<root>/node_modules'] 配合 alias,避免“幽灵依赖”与“重复 React”问题。
  4. 构建性能优化:extensions 与 mainFiles 顺序务必把最高频匹配项放最前;CI 环境可开启 resolve.cacheWithFileSystem: true(Webpack5 默认开启),并利用 immutablePaths 把 node_modules 设为只读缓存,减少重复 IO,国内美团、快手流水线实测可缩短 8%~12% 构建时长。