reactjswebpackoauth-2.0google-oauthwebpack.config.js

How to use environment variables that were defined in Webpack?


I am currently trying to add Google oauth to a React App I am creating. However I am running into a problem. I have defined some variables in my webpack but when I add them to my react code they are coming up as undefined.

React component code

let googleLoginBaseUrl = 'https://www.google.com/o/oauth2/v2/auth'
    let googleLoginQuery = stringify({
        client_id: __GOOGLE_CLIENT_ID__,
        response_type: 'code',
        redirect_uri: `${__API_URL__}/oauth/google/code`,
        scope: 'openid profile email',
        prompt: __DEBUG__ ? 'consent' : undefined,
    })

    let googleLoginUrl = `${googleLoginBaseUrl}?${googleLoginQuery}`

Webpack.config.js code

let plugins = [
  new EnvironmentPlugin(['NODE_ENV']),
  new ExtractPlugin('bundle-[hash].css'),
  new HTMLPlugin({template: `${__dirname}/src/index.html`}),
  new DefinePlugin({
    __DEBUG__: JSON.stringify(!production),
    __API_URL__: JSON.stringify(process.env.API_URL),
    __GOOGLE_CLIENT_ID__: JSON.stringify(process.env.GOOGLE_CLIENT_ID),
  }),
]

if (production)
  plugins = plugins.concat([ new CleanPlugin(), new UglifyPlugin() ])

module.exports = {
  plugins,

Compiling Error

Failed to compile.

./src/components/Login/login.js
  Line 10:24:  '__GOOGLE_CLIENT_ID__' is not defined  no-undef
  Line 12:30:  '__API_URL__' is not defined           no-undef
  Line 14:21:  '__DEBUG__' is not defined             no-undef

Search for the keywords to learn more about each error.

Solution

  • It looks like that there is not javascript compile error, but only ESLint reported error. Probably you have set up your build process such way, that some eslint error stops your build process.

    I can confirm that using variables defined with DefinePlugin in the app is reported by ESLint as an no-undef error.

    Try to disble this ESLint rule, put /* eslint-disable no-undef */ on the first line of your ./src/components/Login/login.js.

    Or you can add your defined variables to globals section in your eslint config file, see this answer: ESLint no-undef and webpack plugin