【问题标题】:How to use environment variables that were defined in Webpack?如何使用 Webpack 中定义的环境变量?
【发布时间】:2019-10-04 00:01:30
【问题描述】:

我目前正在尝试将 Google oauth 添加到我正在创建的 React 应用程序中。但是我遇到了一个问题。我已经在我的 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-oauth webpack.config.js


    【解决方案1】:

    貌似没有javascript编译错误,只有ESLint报错。可能你已经设置了你的构建过程,一些 eslint 错误会停止你的构建过程。

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

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

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

    【讨论】:

    • 所以页面现在正在构建,但DefinePlugin定义的环境变量仍然被视为未定义
    • 我可以确认,DefinePlugin 它与您的语法一起正常工作,是不是您在 DefinePlugin 中的变量值有问题?如果您尝试将简单值放入变量中会发生什么情况(例如__DEBUG__ : JSON.stringify('Just for testing'))?如果发生替换,请检查您构建的捆绑包(搜索字符串“Just for testing”)。
    猜你喜欢
    • 2016-11-05
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2020-01-17
    相关资源
    最近更新 更多