添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
爱笑的热带鱼  ·  磁力种子搜索 - 百度·  3 月前    · 
无邪的梨子  ·  Architecture modeling ...·  4 月前    · 
低调的核桃  ·  PowerShell ...·  5 月前    · 
另类的电脑桌  ·  DNS Checker - DNS ...·  6 月前    · 

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

🐛 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
    luke-j, tomashapl, iam4x, robin-ambachtsheer, eddyerburgh, pietdevries94, sshrshnv, sandcastle, shrpne, VaclavSir, and 124 more reacted with thumbs up emoji Sagnik-Chaudhuri and ibrahimBeladi reacted with heart emoji All reactions

    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...

    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.

    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 ?

    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.

    kristiehowboutdat, dbellizzi, kontrollanten, Josh-Drubin-Zocdoc, dhatawesomedude, kalinchernev, getneil, shrpne, maxime1992, fesaza, and 35 more reacted with thumbs up emoji MaffooBristol and ValentinnDimitroff reacted with thumbs down emoji maxime1992, fesaza, nachocodoner, aledalgrande, Rocss, peller, AdamFerguson, vojdan, tjmoses, vitormv, and 9 more reacted with hooray emoji FlorianWendelborn, tlux, and Khvoya reacted with confused emoji maxime1992, george-cana, nachocodoner, aledalgrande, kamilmielnik, josipovich, vitormv, sagaban, swapneeldesai, liuliangsir, and 3 more reacted with heart emoji maxime1992, mzablocki, nachocodoner, jdeniau, sagaban, swapneeldesai, liuliangsir, dancamma, and vilanz reacted with rocket emoji idobleicher, EugeneDraitsev, dao-heart, sagaban, swapneeldesai, liuliangsir, dancamma, vilanz, and ibrahimBeladi reacted with eyes emoji All reactions

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

  • Changing the filename .babelrc to babel.config.js and module.exports the config object
  • 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$"
      fhadsheikh, kristiehowboutdat, esoulie1, petermikitsh, artkravchenko, royipressburger, davidlandais, davidpelayo, PaulRosset, gdad-s-river, and 200 more reacted with thumbs up emoji
      theus, kassyn, icunningham88, zainfathoni, Schnueggel, ielgnaw, zzis, bbenezech, pinkeygupta, harry-schurr, and 18 more reacted with laugh emoji
      jelixson, kristiehowboutdat, daviestar, petermikitsh, davidlandais, camdenbrown-zz, davidpelayo, lemoustachiste, gdad-s-river, morgler, and 85 more reacted with hooray emoji
      kjkta, genie-youn, Ajay-Kandakatla, shayc, ajaymathur, djforth, haikov, goranovs, mikeumus, jastkand, and 42 more reacted with heart emoji
      goranovs, mikeumus, theus, kassyn, Altiire, zainfathoni, Schnueggel, ielgnaw, JeremiahChurch, zzis, and 22 more reacted with rocket emoji
      theus, kassyn, idobleicher, bbenezech, harry-schurr, rodriguez-facundo, dmp359, zemuldo, reenan, centerorbit, and 9 more reacted with eyes emoji
        All reactions
          
    babel-jest requires babel config to be stored in .js file
    to transform JSX expressions via @babel/preset-react.
    See jestjs/jest#6229 (comment)
    ~/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?

    davidpelayo, ryansully, drphelps, Jiert, wilzbach, jeffryang24, tkrotoff, macko911, chin2km, dimadk24, and 35 more reacted with thumbs up emoji mrchief, komali2, willyyang, EyMaddis, laryssamagalhaes, renanbronchart, AndrewRayCode, aroc, sumthief, renmm, and 37 more reacted with thumbs down emoji alxrl, shprink, zainfathoni, karl-frascari, dicrescenzoa, and liuliangsir reacted with laugh emoji brandonFaf, zainfathoni, karl-frascari, dicrescenzoa, and liuliangsir reacted with hooray emoji vkartaviy, birdream, saicharanp, chris-washington, smilyanp, robolivable, renmm, komali2, mMarcos208, andreisocaciu, and 4 more reacted with confused emoji dwiyatci, brandonFaf, zainfathoni, perakerberg, dicrescenzoa, tpluscode, and liuliangsir reacted with rocket emoji All reactions gdad-s-river, nickovchinnikov, colinrobertbrooks, dferber90, blackcater, leeran88, zainfathoni, Avanti24, imollov, and liuliangsir reacted with hooray emoji komali2, ikiyou, vkartaviy, chin2km, putan, dwiyatci, pak11273, syafilm, leoyli, ralphkrauss, and 3 more reacted with confused emoji escapedcat, leeran88, zainfathoni, and liuliangsir reacted with heart emoji dwiyatci reacted with eyes emoji All reactions

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

  • it's better to have a separate jest.config.js
  • 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 )
  • 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',
    
  • npm test again. make sure your package.json test:, is scripted correctly.
  • veken1199, avakarev, nickovchinnikov, andreystepanov, elsonlim, jianglin101, vik-addweb, ebongso, zainfathoni, rachelslurs, and 5 more reacted with thumbs up emoji veken1199, nickovchinnikov, zainfathoni, rachelslurs, deju, liuliangsir, and dpwiese reacted with hooray emoji vik-addweb, zainfathoni, rachelslurs, deju, liuliangsir, and dpwiese reacted with heart emoji ankita1010 and liuliangsir reacted with eyes emoji All reactions
  • 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',
      MikeMitterer, PierrickGT, liuliangsir, xx4159, nottoseethesun, and shwnyao reacted with thumbs up emoji
      joshuarobs reacted with thumbs down emoji
      adamelkhayyat and liuliangsir reacted with heart emoji
        All reactions
              

    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.

    @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.

    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.

    WizardCM, btilford, ethankore, joshuarobs, GuilhermeLLS, enagorny, justinfarrelldev, GiridharKarnik, tsimons, josephfinlayson, and 5 more reacted with thumbs up emoji elyobo reacted with thumbs down emoji All reactions

    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.