So I am creating an application with:
React
16.4.0
Electron
2.0.2
Webpack
4.11.0
I am now able to compile and run the app with webpack (webpack dev server
). The problem is that I only want to show the Chrome dev tools in development mode. This is something I can manage from the main.js
file of Electron. But the problem is that I do not want to do it manually.
So logically I want to do this via the process.env.NODE_ENV
variable. This variable is set by Webpack in the webpack-config. The problem is that when I try to access the variable in the main.js file I get an undefined
instead of 'development' or 'production'.
Webpack.common.js
const path = require('path');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
resolve: {
modules: [path.resolve(__dirname), 'node_modules']
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['env', 'react'],
plugins: ['transform-runtime'],
env: {
production: {
presets: ['react-optimize']
}
}
}
}
]
}
};
Webpack.dev.js
const webpack = require("webpack");
const merge = require("webpack-merge");
const common = require("./webpack.common");
const path = require("path");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
module.exports = merge(common, {
mode: "development",
entry: ["react-hot-loader/patch", path.join(__dirname, "src", "index.js")],
devtool: "eval-source-map",
plugins: [
new BundleAnalyzerPlugin({ //Make bundle sizes visible
analyzerMode: "static",
openAnalyzer: false
}),
new webpack.HotModuleReplacementPlugin() // Enable hot module replacement
]
});
Since Webpack V4
the NODE_ENV
must be set via the mode
parameter.
Main.js
Below is an abstract version of the file:
const isDevelopement = (process.env.NODE_ENV === "development");
console.log("Result: ", process.env.NODE_ENV); // Results in Undefined
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false, // For security reasons
devTools: isDevelopement
}
});
}
So I was wrong. Webpack mode
sets the iternal NODE_ENV only for compile time. It does NOT update the global NODE_ENV
. So you must still use the webpack.definePlugin
:
new webpack.DefinePlugin({ //Set the node env so that the project knows what to enable or disable
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
Now I can access the NODE_ENV variable in my application. But I can still not access this variable in the main.js
file of Electron.
Why does this result in undefined and what should I change?