I am trying to webpack all the main.js script & its dependencies in a single file (I want to have one file for the UI app, and one file for the server app).
If I use the normal source, index.html loads just fine. However, when webpacking, I get the error mentioned in the title.
Here's the webpack config I used:
webpack({
entry: [
'./main'
],
output: {
path: path.join(__dirname, 'asar'),
filename: 'main.js',
libraryTarget: 'commonjs2'
},
externals: ['electron'],
target: 'node'
});
I load the file like this:
mainWindow.loadURL('file://' + __dirname + '/index.html');
I think that its perhaps due to webpack calling/evaling stuff outside of the electron context that allows serving local files.
Any ideas/suggestions? Thanks!
You can probably try turning off webSecurity
in webPreferences
of BrowserWindow
. For more questions I suggest seeking help from the community.
@MihaiValentin Hey, did you find a solution for this?
@MihaiValentin @singhshashi I had the same problem. It seems webpack, by default, tries to "mock" Node globals like __dirname
. I disabled this behavior with the node.__dirname
option and… it worked!
Just in case, I'm also using webpack-target-electron-renderer for the target
option.
This is my config so far. I hope it helps:
var webpack = require('webpack');
var path = require('path');
var webpackTargetElectronRenderer = require('webpack-target-electron-renderer');
var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: APP_DIR + '/index.js',
output: {
path: BUILD_DIR,
filename: 'index.js'
},
node: {
__dirname: false,
__filename: false
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
exclude: /node_modules/,
loader : 'babel'
}
]
}
};
config.target = webpackTargetElectronRenderer(config);
module.exports = config;
@eiriarte Thanks for sharing that, however that did not work. If I pack the files for the main process using webpack, even with the node configuration that you have said, I still get the same error.
I am sharing a workaround that I am using to get around the issue for others who land on this thread.
Instead of using es features which require babel to transpile them to work correctly in the main. js file, I separated these out into different files. In my main.js I do not use any features which require babel transpilation. So instead of import I use require. For code which was using es7 proposal features such as async, I moved that code to different files, within a folder called desktopServices (you could come up with a better name). I now run webpack to create a bundle for desktopServices and I reference this bundle in main.js.
const myshell = require('./dist/desktopServices').myShell
;
My webpack.config.main.js file contains the following config.
let config = {
target:'electron',
entry:'./desktopServices/desktopServices.js',
output:{
path:path.resolve(__dirname, 'dist'),
filename: 'desktopServices.js',
publicPath:'/dist/',
libraryTarget:'commonjs2'
},
resolve: {
extensions:["",".js",".json"]
},
module: {
noParse: /node_modules\/json-schema\/lib\/validate\.js/,
loaders:[{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json/,
loader: 'json-loader',
},
],
},
}
module.exports = config;
Not the cleanest way, but I guess this is the route I am taking for the time being till some of the es features I want to use get incorporated into node and don't require babel transpilation.
For me, it turned out to be a misleading error. I was getting the not allowed to load local resource
error because webpack hadn't finished writing the file before I was trying to load it, not because it was there with the wrong permissions.
I ~fixed~wrapped it with setTimeout
(the duct tape of javascript) so I could get on with life:
setTimeout(() => {
win.loadURL(`file:///${__dirname}/index.html`);
}, 2000); // 1 second wasn't enough lol
for me.. the reason was because the path the webpack was outputting the bundle.. was out of reach... i solved it by coming back a few directories and applying the node config as suggested above.. works perfectly :D
pathname: path.join(__dirname, '../../source/resources/views', 'index.html');
node: {
__dirname: false,
__filename: false
},
FYI to those here via google: you get the same error if the file doesn't exist. I forgot to tell electron-packager to copy the target file into the app. Learn from my stupid mistakes :)
For future reference (as I've searched through this page too many times), here are the current possible problems:
The file doesn't exist, or your Node application can't reach it. Make sure electron-packager
is copying the target file into the app!
You might need to disable webSecurity
within webPreferences
when you create your BrowserWindow()
:
{
webPreferences: {
webSecurity: false
}
}
node.__dirname
, you can disable this by adding the following to your config: node: {
__dirname: false
}
setTimeout()
(not recommended) or waiting for the ready
event being sent from the app (better).setTimeout(() => {
win.loadURL(`file:///${__dirname}/index.html`);
}, 2000); // 1 second wasn't enough lol
app.on('ready', () => {
win.loadURL(`file:///${__dirname}/index.html`);
})
For me the solution was
Hope this helps someone nube like me.
I'm loading http://localhost:8080/
on my main browser window for the webpack dev server (so i can get hot module reloading). Problem was that when loading with the file://
protocol on an <iframe>
it didn't work.
I simply disabled web security as pointed out by @popey456963 .
I have two configurations for webpack each for the electron-main
and electron-renderer
const path = require('path');
const config_main = {
target: 'electron-main',
entry: path.resolve(__dirname, 'src/main/index.js'),
output: {
path : path.resolve(__dirname, 'static'),
filename: 'main.js'
},
externals: [{ 'electron-store': 'require("electron-store")' }],
resolve: {
alias: {
main : path.resolve(__dirname, 'src/main/'),
common : path.resolve(__dirname, 'src/common/')
}
}
};
const config_renderer = {
target: 'electron-renderer',
entry: path.resolve(__dirname, 'src/renderer/index.js'),
output: {
path : path.resolve(__dirname, 'static'),
filename: 'renderer.js'
},
externals: [{ 'electron-store': 'require("electron-store")' }],
resolve: {
alias: {
components : path.resolve(__dirname, 'src/renderer/components/'),
core : path.resolve(__dirname, 'src/renderer/core/'),
states : path.resolve(__dirname, 'src/renderer/states/'),
ui : path.resolve(__dirname, 'src/renderer/ui/'),
common : path.resolve(__dirname, 'src/common/'),
}
}
};
module.exports = [
config_main,
config_renderer
];
I have tried applying
node: {
__dirname: false
},
I have console'd out in my renderer.js
the __dirname
and in both cases if I have __dirname set to false or true they both print out /
Of course if I manually put in the absolute url it works, though unsure why __dirname
refuses to give the correct path.
webpackTargetElectronRenderer
is the same thing as target: electron-main
I believe at some point electron-main
was rolled into webpack making webpackTargetElectronRenderer
obsolute
Here you can see what electron-main
does
https://github.com/webpack/webpack/blob/master/lib/WebpackOptionsApply.js#L70-L185
Here you can see exact same code.
https://github.com/chentsulin/webpack-target-electron-renderer/blob/master/index.js
Turns out I had
node: {
__dirname: false
},
In my renderer config instead of my main config. I will keep my comment above in case anyone likes my config file.
What if I am not using webpack?
@hbgdPro Try some of the options from https://github.com/electron/electron/issues/5107#issuecomment-299971806, 1, 2 and 4 all don't require webpack.
@popey456963 Thanks. I had already tried before I asked. My problem was actually I had to specify which folders I needed to include in build process. It has nothing to do with webpack.
I just came across this myself, (hi I'm from the webpack team). We have a electron-main target in webpack, and I did not know that the__dirname
and __filename
mocks break the default quick-start example.
Just to make sure, electron team. Would this be an official recommendation to have this disabled? If so I will go ahead and PR our defaults for the electron-main target that we have so that these builtins are not mocked.
Thanks!
@TheLarkInn __dirname
and __filename
are super critical for most electron apps as they are used to find the path to the HTML file to show in the renderer process. Mocking them breaks things most/all the time. Not mocking them would fix many peoples problems 👍
For those not using Webpack i stumbled across a weird solution that i am hoping someone with more experience can elaborate on. I was using the following and receiving the error mentioned throughout this thread.
win.loadURL('file://${__dirname}/renderer/main.html')
after switching the above code to the following the error was gone, and the html would render.
win.loadURL('file://' + __dirname + '/renderer/main.html')
It seems like the original was giving an improper path to the html file for some reason, does anyone know why?
@s-lawrence The improper path is due to:
win.loadURL('file://${__dirname}/renderer/main.html')
Should be
win.loadURL(`file://${__dirname}/renderer/main.html`)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Ah ok that makes sense. Thank you @milewski for elaborating on that as well as providing a reference.
I usually stick with concatenating, but now that I know the proper syntax I’ll start using template literals more, they’re a much cleaner look.
@milewski , I don't see a difference in your two snippets. Is the second one supposed to be different than the first one?
@jakehockey10 The second one has backticks instead of single quotes,. The backticks indicate it's a template literal rather than just a string literal. The first example is a regular string literal, so the ${__dirname}
part never gets substituted with the __dirname
value. It's pretty hard to notice sometimes if your editor doesn't highlight them differently (the GFM syntax highlighter doesn't distinguish them, unfortunately).
Ah gotcha. I didn't notice that difference when viewing it in GitHub's Markdown, but I use Visual Studio Code and definitely notice the difference there as you mention. Sorry for the false alarm ;-)
Just thought I'd add, I also got this error due to my own blunder (cap sensitivity)
I was calling pathname: path.join(__dirname, 'Views/settingsWindow.html')
when the file name was all lower case.
This only casued an error once it was webpacked.
I tried some of the solutions but couldn't get it to work (using [email protected] with [email protected]).
I found the best solution in a post with only 3 votes on SO: Turns out there is no need for this package!
https://stackoverflow.com/questions/45041364/angular-electron-webpack-live-reloading
Zero config-hassle solution:
-npm uninstall electron-reload
-Run ng serve in one terminal
-in main.js change win.loadURL(http://localhost:4200/index.html
);
-then run npm run electron in another terminal
It just WORKS
I Tried to fix this my whole day & finally this guys solution worked do check
https://github.com/electron-userland/electron-builder/issues/2955#issuecomment-393524832
When you define the "build" attribute in the package.json, just add required files as following:
"files": [
"./build/**/*",
"./index.html",
"./src/*.js"
],
Then the electron-builder will pack it correctly.
Turned out for that the 'file://' prefix was all i needed for the loadUrl method.
Had:
win.loadUrl(path.join(__dirname, "./index.html"))
Replaced with:
win.loadUrl(path.join("file://",__dirname, "./index.html"))
Webpack baffles me mixing both forward and backward slashes in the URL to the html entry, so I use node's url
and path
to make it work:
const winURL = process.env.NODE_ENV === 'development'
? 'http://localhost:9080'
: url.format({
protocol: 'file',
pathname: path.join(__dirname, 'index.html'),
});
it is a disaster, I am stuck in CRA + electron 😂, running in dev mode is okay, but packaged into windows exe does not work at all.
I got it. 🤣 If you use CRA with react-router, you should use HashRouter, not BrowerRouter. DONE!!! 😂 refer to https://github.com/electron-userland/electron-builder/issues/2167
Most helpful comment
FYI to those here via google: you get the same error if the file doesn't exist. I forgot to tell electron-packager to copy the target file into the app. Learn from my stupid mistakes :)