Jest not parsing es6: SyntaxError: Unexpected token import

前端 未结 3 734
一个人的身影
一个人的身影 2021-02-19 00:45

I am trying to setup Jest with my webpack project. When I run my tests, Jest complains it cannot read es6 code. Babel seems to not transform my test files.

I have tried

3条回答
  •  [愿得一人]
    2021-02-19 00:57

    You need to do two things:

    1. Create a Babel config file (babel.config.js):

      This is necessary because babel-jest relies on a traditional Babel config file, not webpack. Since version 7 Babel has supported JS configs as babel.config.js.

      When using a JS Babel config (as opposed to a .babelrc, for example) Jest also compiles modules in node_modules. AFAIK by convention this must be in the root of your project, alongside the jest configuration file.

      Here is a config based on the Babel options in your webpack.config.js file:

      // babel.config.js
      module.exports = {
        presets: [
          '@babel/preset-env',
          '@babel/preset-react',
          '@babel/preset-flow',
        ],
        plugins: [
          'babel-plugin-styled-components',
          '@babel/plugin-proposal-class-properties',
        ]
      }
      
    2. Install the babel-core bridge version:

      npm install babel-core@7.0.0-bridge.0 --save-dev
      

      From github.com/babel/babel-bridge:

      This repo holds what we're calling a "bridge" package that is meant to ease the transition for libraries that use "babel-core" as a peer dependency for Babel 6.

      The issue with Babel 7's transition to scopes is that if a package depends on Babel 6, they may want to add support for Babel 7 alongside. Because Babel 7 will be released as @babel/core instead of babel-core, maintainers have no way to do that transition without making a breaking change. e.g.

提交回复
热议问题