[英]Environment variable is undefined in electron even it has been set inside webpack.DefinePlugin
[英]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'
}),
]
}
我定义了 2 个变量 APIHOST 和 BLOCKCHAINHOST 并尝试在 reactjs App.js 中进行控制台记录,就像这样
componentDidMount() {
console.log(APIHOST)
}
我得到的错误是 APIHOST 未定义。 我不确定在这里做什么,我尝试为 webpack.defineplugin 添加单引号,所以它看起来像 'APIHOST': JSON.stringify('test') 但它仍然给我同样的错误。
你可以这样做
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
然后在你的代码中
process.env.NODE_ENV
我使用的版本是
"webpack": "^4.29.6"
看起来这是一个已知问题:
https://github.com/webpack/webpack/issues/1977
DefinePlugin 在 React 组件中不起作用
稍后在 Webpack 3 中修复:
这是固定的。 从 webpack 3 开始,解析器现在完全理解 ES6 语义。
你用的是什么版本? 升级有意义吗?
// eslint-disable-next-line no-undef
可能是eslint的问题,设置了检查,严格的,在编译时不让通过了,然后使用到该变量的地方加上这句注释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.