我在 webpack.DefinePlugin 中定义的变量未定义

ale*_*exW 5 javascript ecmascript-5 ecmascript-6 reactjs webpack

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'
    }),
  ]
}
Run Code Online (Sandbox Code Playgroud)

我定义了 2 个变量 APIHOST 和 BLOCKCHAINHOST,我尝试在 ReactJS App.js 中控制台记录它,如下所示

componentDidMount() {
    console.log(APIHOST)
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误是 APIHOST 未定义。我不知道在这里该怎么做,我尝试为 webpack.defineplugin 添加单引号,所以它看起来像 'APIHOST': JSON.stringify('test') 但它仍然给我同样的错误。

Dre*_*ano 1

看起来这是一个已知问题:

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

DefinePlugin 在 React 组件中不起作用

稍后在 Webpack 3 中修复:

这是固定的。从 webpack 3 开始,解析器现在完全理解 ES6 语义。

您使用什么版本?升级有意义吗?