简体   繁体   中英

Configure babel to compile a specific package inside node_modules when testing with jest

By default, babel skips everything in node_modules. But I have one module under /nodemodules/special-module which is jsx, and needs compilation.

When building the main app, I solve this in webpack.config.json by including this in the rules array:

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

But webpack is not used when running tests with jest. I get an error showing that special-module is not being compiled.

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

Instead, options have to be set in .babelrc where the equivalent should be

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

My understanding is that supplying an ignore key prevents the default exclusion of node_modules , ignoring only files matching the given regex. But the above does not seem to work. The special-module is still not compiled. This is using bable 6.23.0, so this bug should not be a problem.

Finally figured it out. Rather than putting the ignore in .babelrc it needs to go in the transformIgnorePatterns jest setting in package.json

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

In fact I found I didn't need a .babelrc at all, as babel-jest is automatically installed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM