Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

babel-jest does not transpile import/export in node_modules when Babel 7 is used #6229

Closed
dantman opened this issue May 22, 2018 · 58 comments
Closed

Comments

@dantman
Copy link

dantman commented May 22, 2018

🐛 Bug Report

I started getting the dreaded SyntaxError: Unexpected token import error again for lodash-es. And I spent hours debugging it, because I already had .babelrc and package.json:jest configured properly ("modules": "commonjs", a jest.transform for babel-jest, and transformIgnorePatterns set to not ignore node_modules/lodash-es).

After a lot of debugging and a little searching, it appears that Babel 7 has stopped using the project's .babelrc code in node_modules. This means that all the previous suggestions to just tell transformIgnorePatterns to transpile certain packages in node_modules and set "modules": "commonjs" in the test env to make WebPack import work with jest no longer work.

To Reproduce

Steps to reproduce the behavior:

  • Import an es-modules using library like lodash-es into your project
  • Write a Jest test that imports the file you import the es-modules using package
  • Setup a recent version of Babel 7
  • Configure .babelrc to use the env preset to transpile ES6 modules to CommonJS
  • Configure Jest to transform .js files with babel-jest and transformIgnorePatterns to not ignore the es-modules using package

Expected behavior

When babel-jest is used to transpile ES-modules using packages like lodash-es it should transpile the imports to CommonJS so they work with Jest.

Practically I believe it should be sufficient to add transform-modules-commonjs to the plugins list that babel-jest uses when the filename is a node_modules file and Babel 7 is used. This would also fix the fact that it's not good practice for the project's .babelrc (which may also include plugins for non-standard things like JSX and flow) to be used just to transpile ES6 / modules code in packages.

Link to repl or repo (highly encouraged)

https://gist.github.com/dantman/820f6232acc6f53bd1e57d21b09e1f89

Run npx envinfo --preset jest

Paste the results here:

  System:
    OS: macOS Sierra 10.12.6
    CPU: x64 Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz
  Binaries:
    Node: 9.11.1 - ~/.nvm/versions/node/v9.11.1/bin/node
    Yarn: 1.6.0 - /usr/local/bin/yarn
    npm: 5.6.0 - ~/.nvm/versions/node/v9.11.1/bin/npm
  npmPackages:
    jest: ^22.4.4 => 22.4.4
@SimenB
Copy link
Member

SimenB commented May 23, 2018

I don't think Jest should add babel transforms, beyond the ones it needs for its own purposes.

That said, Jest should load your babel config itself, so weird that it doesn't work...

@dantman
Copy link
Author

dantman commented May 23, 2018

babel-jest doesn't load the confic, it reads it and uses it for caching, but to my knowledge it leaves babelrc handling up to Babel as it should.

However Babel no longer uses project config inside node_modules. So the only one able to add config for node_modules at this point is babel-jest.

@SimenB
Copy link
Member

SimenB commented May 23, 2018

babel-jest doesn't load the confic, it reads it and uses it for caching, but to my knowledge it leaves babelrc handling up to Babel as it should.

Oh, you're correct, I confused it with the merge done by the createTransformer factory.

This seems more like a Babel issue rather than Jest, though. Is there an issue over there about it, and discussing the use case of transpiling node_modules?

@dantman
Copy link
Author

dantman commented May 23, 2018

No, this is a change they explicitly made. They decided project config shouldn't affect node_modules, which is entirely reasonable since project config can contain stage-0, react/jsx, flow and other things that should not be used in packages. So it doesn't make sense for this to be considered a Babel bug or have an issue there.

They explicitly decided .babelrc should not affect node_modules. And they already give whoever is calling babel-core to transform files the ability to define plugins/presets that will run on the file even if it is in node_modules. Babel isn't doing anything unreasonable.

@luke-j
Copy link

luke-j commented May 25, 2018

Any updates on this? This is behaviour which was working before and is now not, which seems to be to be a clear regression. Fair enough if the behaviour is to be removed, but lacking any clear documentation indicating that, this just feels like a bug.

@mpospelov
Copy link

I had the same issue and I found this comment.
So you should rename the .babelrc file to babel.config.js which will export .babelrc object.

@luke-j
Copy link

luke-j commented May 28, 2018

Thanks for the suggestion @mpospelov. Unfortunately, it didn't seem to work for me.

@manico
Copy link

manico commented May 29, 2018

I have a problem on Mac also.
When I updated node modules cannot run tests anymore.
It fails to transpile from node_modules package even tough I set transformIgnorePatterns (did not change them since it worked).

antongolub added a commit to qiwi/uniconfig that referenced this issue Jun 8, 2018
@macrozone
Copy link

this happend to me when i updated a react-native project to 0.56.0. Since then, jest test can't be run anymore. transformIgnorePatterns seems to be completly ignored.

@austinkelleher
Copy link

Any additional thoughts on this @SimenB? I'm also seeing this issue.

@fhadsheikh
Copy link

I've got the same issue as @marcelerz. Ever since updating to React Native 56.0, transformIgnorePatterns seems to be ignored.

@austinkelleher
Copy link

austinkelleher commented Jul 9, 2018

For the record, I was able to fix the issue of my module in the node_modules folder not compiling properly by:

  1. Changing the filename .babelrc to babel.config.js and module.exports the config object
  2. Adding transformIgnorePatterns to my Jest config:
"transformIgnorePatterns": [
  // Change MODULE_NAME_HERE to your module that isn't being compiled
  "/node_modules/(?!MODULE_NAME_HERE).+\\.js$"
]

@w3z315
Copy link

w3z315 commented Aug 15, 2018

Thanks @austinkelleher

We had something similar but a bit different,

your fix didn't work first - but then we realized that we were missing the .+\\.js$ at the end of the line, which worked just fine with jest and babel 6 but doesn't with babel 7.

artkravchenko added a commit to artkravchenko/production-react-boilerplate that referenced this issue Aug 19, 2018
babel-jest requires babel config to be stored in .js file
to transform JSX expressions via @babel/preset-react.
See jestjs/jest#6229 (comment)
@nickovchinnikov
Copy link

nickovchinnikov commented Sep 7, 2018

  ● Test suite failed to run

    ~/internals/jest/settings.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Enzyme from 'enzyme'
                                                                                                    ^^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

package.json

"jest": {
    "transform": {
      "^.+\\.(js|jsx|ts)$": "babel-jest",
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/internals/jest/fileTransform.js",
      "\\.(css|less)$": "<rootDir>/internals/jest/cssTransform.js"
    },
    "setupTestFrameworkScriptFile": "<rootDir>/internals/jest/settings.js",
    "testURL": "http://localhost/"
  }

Versions:

"jest": "^23.5.0",
"babel-jest": "^23.4.2"

/internals/jest/settings.js

import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new Adapter() })

Could you please help?

@norbertkeri
Copy link

Renaming .babelrc to babel.config.js worked for me

@SimenB
Copy link
Member

SimenB commented Sep 11, 2018

See #6053 (comment), it explains the need for babel.config.js. I don't think Jest should do anything special here, open to being convinced otherwise, though.

@komali2
Copy link

komali2 commented Oct 17, 2018

SimenB, that solution is not working for vue-cli.

vuejs/vue-cli#1584

We don't have .babelrc, or .babel.config.js. I tried creating a basic one, it didn't work.

@moon004
Copy link

moon004 commented Oct 27, 2018

@MasteR-7 , i had similar problem, my advice to u is the followings:

  1. it's better to have a separate jest.config.js
  2. yarn add --dev babel-jest babel-core@^7.0.0-bridge.0 @babel/core regenerator-runtime (look at https://jestjs.io/docs/en/getting-started.html#using-babel )
  3. create a babel.config.js file, and put the following code inside.
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
  ],
  env: {
    test: {
      presets: [
        '@babel/preset-env',
        '@babel/preset-react',
      ],
      plugins: [
        '@babel/plugin-proposal-class-properties',
        'transform-es2015-modules-commonjs',
        'babel-plugin-dynamic-import-node',
      ],
    },
  },
};
  1. npm test again. make sure your package.json test:, is scripted correctly.

@Dip686
Copy link

Dip686 commented Feb 25, 2020

faced the same issue, followed this steps to resolve

  1. install babel-jest
  2. in jest config add this configuration
transform: {
       '^.+\\.js?$': require.resolve('babel-jest')
   }
  1. make sure you have babel.config.js present (your config might be different than provided below)
module.exports = {
  "env": {
    "test": {
      presets: [
        [
          '@babel/preset-env',
          {
            targets: {
              node: 'current',
            },
          },
        ],
      ]
    }
  }
};

@OsirisRoman
Copy link

OsirisRoman commented Apr 24, 2020

I got this problem while trying to make run npm test

https://stackoverflow.com/questions/61391878/problem-while-testing-es6-class-with-jest

@jtbandes
Copy link

I ran into a similar error when trying to import a package from node_modules whose index.js is an ES Module. After a lot of painful debugging, I was able to resolve it by moving my babel configuration out of package.json, into babel.config.js, as described here: #6053 (comment) Combined with a custom transformIgnorePatterns (see here), this allowed babel-jest to correctly transform the file in node_modules.

@OsirisRoman
Copy link

OsirisRoman commented Apr 25, 2020

@jtbandes I made the changes you suggest. I rename the file .babelrc by babel.config.js. I also add the jest.config.js file and I removed the jest configuration from package.json. But now when I run npm run test then this error appears:

babel.config.js: Error while loading config - Unexpected token ':

My babel.config.js has this content:

{
"presets": ["es2015"]
}
why the colon punctuation is a problem?

Pd. Now the npm run production command is not working anymore. Now babel is not capable of transpile the export keyword. Before the suggestion the transpilation of the code running ok, the only problem was just the testing with jest while running npm run test.

@jtbandes
Copy link

babel.config.js is a JS file, not a JSON file. You need to use module.exports = ...

@WizardCM
Copy link

WizardCM commented Apr 29, 2020

Man I spent countless hours trying to figure out why transformIgnorePatterns wasn't working, and this was the cause all along? That I wasn't explicitly using babel.config.js? I understand why, but dang. I was using "babel": in package.js.

Maybe the error that's displayed below when there's an unexpected token should explicitly state that it only works with babel.config.js?

Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.

@N8BAUER
Copy link

N8BAUER commented Oct 30, 2020

The error handling for this issue needs to be updated with a direct link to the solution unless a fix is going to be implemented as it's quite absurd how obscure and nonsensical this issue is still ongoing in 2020. On second thought, if you consider it's 2020 it's quite the norm. Good day

@SimenB
Copy link
Member

SimenB commented Oct 30, 2020

Feel free to send a PR improving the error

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests