【问题标题】:Configure babel to compile a specific package inside node_modules when testing with jest使用 jest 进行测试时,配置 babel 以编译 node_modules 中的特定包
【发布时间】:2018-02-21 03:26:49
【问题描述】:

默认情况下,babel 会跳过 node_modules. 中的所有内容,但我在 /nodemodules/special-module 下有一个模块,即 jsx,需要编译。

在构建主应用程序时,我在 webpack.config.json 中通过将其包含在 rules 数组中来解决此问题:

{
  test: /\.jsx?$/,
  exclude: /node_modules(?!\/(special-module))/,
  loader: 'babel-loader',
  query: {presets: ['es2015', 'react']}  // to transform JSX into JS
}

但是用 jest 运行测试时不使用 webpack。我收到一个错误,显示未编译特殊模块。

.../myproject/node_modules/special-module/src/Special.jsx:151
                <div>
                ^    
SyntaxError: Unexpected token <

相反,必须在 .babelrc 中设置选项,其中应该是等效项

{
  "presets": ["es2015", "react"],
  "ignore": "node_modules\/(?!special-module)"
}

我的理解是,提供 ignore 键可以防止默认排除 node_modules,只忽略与给定正则表达式匹配的文件。但以上似乎不起作用。 special-module 仍未编译。这是使用 bable 6.23.0,所以this bug 应该不是问题。

【问题讨论】:

    标签: reactjs jestjs babeljs


    【解决方案1】:

    终于想通了。与其将忽略放在.babelrc 中,不如将它放在transformIgnorePatterns jest settingpackage.json

      "jest": {
        "transformIgnorePatterns": [
          "<rootDir>/node_modules/(?!special-module)"
        ]
        ...
      }
    

    事实上,我发现我根本不需要.babelrc,因为babel-jestautomatically installed

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 2019-08-25
      • 2020-03-11
      • 1970-01-01
      • 2019-10-25
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多