2

I need some linting rules to throw either an error or a warning depending on whether the build is development or production. In a React component file during development process.env.NODE_ENV === 'development'.

In eslintrc.js I have:

const production = process.env.NODE_ENV !== 'development'; // returns true
console.log('%c process.env.NODE_ENV', 'color: green;', process.env.NODE_ENV); // returns undefined

I want to be able to switch between linting rule warnings. and errors like this:

    rules: {
        'no-tabs': 0,
        indent: [2, 'tab', { SwitchCase: 1, VariableDeclarator: 1 }],
        'react/jsx-props-no-spreading': 'off',
        'no-unused-vars':
            production
                ? 'error'
                : 'warn',

Why is process.env.NODE_ENV undefined and how can I fix this?

1
  • I would imagine any environment variables would be undefined during static analysis in your IDE since the code isn't actually running in an environment. Commented Oct 30, 2020 at 17:22

2 Answers 2

2

Since it's undefined during static analysis you can always do something like this:

  'no-console': (() => {
      if (typeof process.env.NODE_ENV === 'undefined') {
        return 'off';
      }

      if (process.env.NODE_ENV === 'development') {
        return 'off';
      }

      return 'error';
    })(),
Sign up to request clarification or add additional context in comments.

1 Comment

I was struggling to set rule only to development and this works for me! Thank you so much!
0

You might think about just having multiple configuration files for eslint instead of trying to handle environment changes in a single file.

According to the docs: https://eslint.org/docs/user-guide/command-line-interface#basic-configuration

You can just call eslint with the -c or --config flags and pass in the extra config file. This will merge a base config file with the file passed in the flag

An example for two lint scripts:
eslint --config ./dev-config.js **/*.js
eslint --config ./prod-config.js **/*.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.