简体   繁体   中英

process.node.env is undefined in eslintrc.js

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?

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

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';
    })(),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM