如何使用Webpack中定义的环境变量?

问题描述 投票:0回答:1

我目前正在尝试将Google oauth添加到正在创建的React App中。但是我遇到了一个问题。我已经在Webpack中定义了一些变量,但是当我将它们添加到我的React代码中时,它们将变为未定义状态。

反应组件代码

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代码

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,

编译错误

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.
reactjs webpack oauth-2.0 google-oauth2 webpack.config.js
1个回答
0
投票

似乎没有javascript编译错误,只有ESLint报告了错误。可能您已经以这种方式设置了构建过程,以致某些错误会停止构建过程。

[我可以确认ESLint将在应用程序中使用通过DefinePlugin定义的变量报告为no-undef错误。

尝试消除此ESLint规则,将/* eslint-disable no-undef */放在./src/components/Login/login.js的第一行。

或者您可以将定义的变量添加到eslint配置文件的globals部分,请参见以下答案:ESLint no-undef and webpack plugin

© www.soinside.com 2019 - 2024. All rights reserved.