Skip to content
Advertisement

How to set env in package.json which is used within .bablerc

I am trying to run Jest tests as part of a script before I then run webpack, like this.

npm run test
webpack --progress --profile --watch --mode development

Jest only works with compiled code, so I had set my .babelrc to the following, which worked, however then it transpiled all my code in webpack which I didn’t want, in development mode I want to leave the JavaScript un-transpiled so I can work with it without it being obfuscated.

{
   "presets": [ "@babel/preset-env" ]
}

Instead I want to run Jest by calling ‘npm run test’ which then I can specify only that script transpiles the code and then webpack runs without transpiling, I was hoping something like this in my .babelrc file

{
    "env": {
      "test": {
        "presets": [ "@babel/preset-env" ]
      }
    }
}

Then in my package.json I could set the env to test which then would leave webpack alone.

"scripts": {
  "test": "SET env=test&& jest --config jest.config.js"
}

With this setup I still get the following message appearing when ‘npm run test’ runs which shows the babelrc file isn’t being hit.

Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it’s not plain JavaScript.

Can anyone help?

Advertisement

Answer

So turns out my test was ok in the .babelrc file

{
    "env": {
      "test": {
        "presets": [ "@babel/preset-env" ]
      }
    }
}

And the script needed in my package.json was this without setting any node env

"scripts": {
  "test": "jest --config jest.config.js"
}

It was actually my webpack script that wasn’t configured correctly, I needed to add ‘–env.NODE_ENV=development’ at the end

webpack --progress --profile --watch --mode development --env.NODE_ENV=development

Which could then be checked within my webpack.config file.

module.exports = (env) => {
    const isDevelopment = env && env.NODE_ENV === 'development';
    ...

then in my rules test for isDevelopment

rules: [{
    test: /.js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
        loader: 'babel-loader',
        options: isDevelopment ? {} : { presets: ['@babel/preset-env'] }
    }
},
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement