node.jsjestjsbabeljsbabel-node

How to use babel-preset-env with Jest


We are in the midst of updating our API, and Henry Zhu from Babel alerted me to this preset called babel-preset-env to replace need for babel-preset-es2015 and babel-preset-es2018.

Now, I am encountering difficulty understanding the simplest way to handle everything.

This will be easier if I just show you the current position of our config:

.babelrc

 {
   "presets": [
     "env",
       {
         "targets": {
           "node": "current"
         }
       },
     "jest"
   ]
 }

package.json

 {
   "scripts": {
     "test": "node --harmony-async-await node_modules/jest/bin/jest.js",
     "start:local": "NODE_ENV=localhost npm run babel-node -- warpcore/server.js",
     "start": "npm run babel-node -- warpcore/server.js",
     "babel-node": "babel-node --presets=es2015,stage-2"
   },
   "dependencies": {
     "babel-polyfill": "^6.23.0"
   },
   "devDependencies": {
     "babel-cli": "^6.24.1",
     "babel-core": "^6.25.0",
     "babel-eslint": "^7.2.3",
     "babel-jest": "^20.0.3",
     "babel-preset-env": "^1.6.0",
     "babel-preset-es2015": "^6.24.1",
     "babel-preset-es2018": "^1.0.0",
     "babel-preset-stage-2": "^6.24.1",
     "jest": "^20.0.4"
   },
   "jest": {
     "testURL": "http://localhost:8080",
     "testEnvironment": "node"
   }
 }

I am uncertain how these things need to be organized to best achieve my bullet list above.

What changes should I make?


Solution

  • I think I got it working. Here is the solution:

    .babelrc

    The one posted in the question has a syntax error because the env preset needs to be wrapped in brackets[] (from: http://babeljs.io/docs/plugins/preset-env/)

    Correct:

     {
       "presets": [
         ["env",
           {
             "targets": {
               "node": "current"
             }
           }],
         "jest"
       ]
     }
    

    package.json

    The one posted in the question has a few things that can be removed:

      {
         "scripts": {
           "test": "jest --verbose",
           "start:local": "cross-env NODE_ENV=localhost babel-node -- app.js",
           "babel-node": "babel-node --presets=env"
        },
        "dependencies": {
          "babel-cli": "^6.24.1",
          "babel-preset-env": "^1.6.0"
        },
        "devDependencies": {
          "babel-eslint": "^7.2.3",
          "babel-jest": "^20.0.3",
          "jest": "^20.0.4"
        },
        "jest": {
          "testURL": "http://localhost:8080",
          "testEnvironment": "node"
        }
      }
    

    Much cleaner in my opinion. You can modulate the presets from the .babelrc file if you want to explicitly include or exclude any, or specify which browsers to support.