Bundle error using webpack for Electron application `Cannot resolve module 'electron'`
Solution 1
Webpack tries to resolve electron
module with the installed node_modules. But the electron
module is resolved in Electron itself at runtime. So, you have to exclude particular module from webpack bundling like this:
webpack.config.js:
module.exports = {
entry: './app.jsx',
output: {
path: './built',
filename: 'app.js'
},
target: 'atom',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx$/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
};
Solution 2
A very simple solution :
const remote = window.require('electron').remote;
webpack will ignore this require
Solution 3
You can set target: 'electron'
in your webpack config and then you don't have to exclude electron in externals.
From webpack documentation:
"electron"
Compile for usage in Electron – supportsrequire
-ing Electron-specific modules.
Related videos on Youtube
MasterT
Updated on September 15, 2022Comments
-
MasterT over 1 year
I am trying to create an Electron application with React. I use Webpack to compile the React JSX syntax, but when I try to compile with
webpack
command, I got this error:ERROR in ./app.jsx Module not found: Error: Cannot resolve module 'electron' in /Users/masterT/Downloads/gist
@ ./app.jsx 6:18-37
Here is the application code.
I am doing something wrong?
Thanks!
-
Maxdow almost 8 yearsnice one ! I don't need to touch the webpack config and it's perfect for me because my environment could be web or electron
-
Pier almost 8 yearswhy is everyone using complicated webpack configs when this simple solution works? are there any drawback?
-
sjmeverett about 7 yearsThis should be the accepted answer: it's the only one that addresses the specific issue.
-
Max Yari about 6 yearsIt seems that this doesn't stop webpack from compiling electron requires into bundle.js. It doesn't throw error - yes - but you will have a broken bundle js with node module copied in it if you'll attempt to require any node-only modules in your jsx's ("path" for ex). At least that what i've experienced using "electron-main" and/or "electron-renderer" targets ("electron" target is depreciated in latest). Seems like using window.require for electron requires works and allows for more control.
-
Venryx over 5 yearsNote that in newer Webpack versions, the correct target name is
electron-main
. -
NamNamNam almost 4 yearsIt works when developing, but after packaged the electron app it doesn't work anymore, any suggestion?
-
vaughan over 2 yearsWon't work with ESM source. The
externals
solution below is better.