1
votes

Application with webpack 2, using eslint.

I'm using DefinePlugin of webpack to replace NODE_ENV variable at compile time. I'm using eslint for code formatting.

This is how I define the variables to be replaced in webpack.config.js,

var plugins = [

    new webpack.DefinePlugin({
        NODE_ENV:JSON.stringify(NODE_ENV)
    }),

    new webpack.ProvidePlugin({
        moment: 'moment',
        _: 'lodash',
    }),
];

This is the eslint loader in webpack config:

{
                test: /\.jsx?$/, // both .js and .jsx
                loader: 'eslint-loader',
                include: path.resolve(process.cwd(), 'src'),
                enforce: 'pre',
                options: {
                    fix: true,
                },
            },

This is how access then the variables in the code:`

if (NODE_ENV === "development") middleware = [...middleware, createLogger()]

Problem:

As I have enabled the eslint rule 'no-undef', when I try to start the app, eslint runs and it gives the error "9:5 error 'NODE_ENV' is not defined no-undef". Because it does not know that NODE_ENV will be replaced by some other text by webpack. If I disable the rule, everything works fine, but of course, I don't want to disable this rule.

Anyone faced a similar problem or know how it can be solved? Thanks!

1

1 Answers

1
votes

You can use this:

new webpack.EnvironmentPlugin([ 'NODE_ENV' ])

And in your code:

if (process.env.NODE_ENV === 'development') ...

This assumes that the NODE_ENV variable in your Webpack config is a copy of process.env.NODE_ENV (in other words, that you set the active Node environment through an environment variable and not, say, a configuration file).

If that's not the case, you can use this:

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
}),