简体   繁体   中英

variables I defined in webpack.DefinePlugin is undefined

webpack.config.js

const path = require('path')
HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'index_bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
            plugins: ["@babel/plugin-proposal-class-properties"]
          }
        }
      },
      {
        test:/\.css$/,
        use:['style-loader','css-loader']
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      APIHOST: JSON.stringify('test'),
      BLOCKCHAINHOST: JSON.stringify('test')
    }),
    new HtmlWebpackPlugin({
      template: './src/template.html'
    }),
  ]
}

I defined 2 variables APIHOST and BLOCKCHAINHOST and I tried to console log this in reactjs App.js like so

componentDidMount() {
    console.log(APIHOST)
}

The error I'm getting is APIHOST is undefined. I'm not sure what to do here, I've tried adding single quotes for webpack.defineplugin so it looks like 'APIHOST': JSON.stringify('test') but it's still giving me the same error.

You can do like this

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

Then in your code

process.env.NODE_ENV

The version I'm using is

"webpack": "^4.29.6"

It looks like this is a known issue:

https://github.com/webpack/webpack/issues/1977

DefinePlugin doesn't work inside React Components

Fixed later on in Webpack 3:

This is fixed. Since webpack 3, the parser now fully understands ES6 semantics.

What version are you using? Does it make sense to upgrade?

// eslint-disable-next-line no-undef

可能是eslint的问题,设置了检查,严格的,在编译时不让通过了 加上使用到该变量的地方的上面加上这句注释

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