【问题标题】:Barrel files, webpack and jest桶文件、webpack 和 jest
【发布时间】:2025-12-16 11:40:01
【问题描述】:

我对桶文件、webpack 和 jest 有一些疑问。我从来没有真正想知道它们是如何工作的,现在我正在努力(开玩笑)在一个还没有测试的更大的应用程序上编写测试。

我在大文件夹中有桶文件(如components),它们看起来像这样:

/components/index.js

export { default as ComponentA } from './ComponentA';
export { default as ComponentB } from './ComponentB';
export { default as ComponentC } from './ComponentC';

通过这样的设置,我可以像这样轻松地导入这些组件:

import { ComponentA, Component C } from '/components';

而不是写作

import Component A from '/components/ComponentA';
import Component C from '/components/ComponentC';

我的主要问题:在我的 webpack 捆绑文件中,是否会因为我在 components/index.js 中有 ComponentB 文件而包含它(但我并没有真正使用它)?

在我开始用 jest 编写测试后,我想到了这件事,它开始向我抛出关于我尚未编写测试的文件的错误。我试图搜索原因,唯一能找到的原因是我从桶文件中导入了更大的文件(例如,我在构建页面时从桶文件导入ComponentA - 我现在正在尝试测试)。

【问题讨论】:

    标签: javascript reactjs webpack jestjs


    【解决方案1】:

    应该支持桶导入,至少如果您使用 ts-jest 转换。 参考:https://github.com/kulshekhar/ts-jest/issues/1149

    但我鼓励桶类型定义 src/types/index.d.ts 出现类似问题,通常在代码库中引用为 @/types

    我最终配置了额外的 moduleNameMapper 定义

     moduleNameMapper: {
        // FIXES Could not locate module @/types mapped as: .../src/types.
        '^@/types$': '<rootDir>/src/types/index.d',
      },
    

    希望这会对某人有所帮助:)

    【讨论】: