I'm trying to use Visual Studio (not VSCode) to create a simple Electron app. I'm doing so via the Node.js tools for Visual Studio (v1.1) extension. I'm using the basic quick start app which works fine if I launch via npm start, but if I launch via Visual Studio, I get the following error on start up:
'Cannot find module 'electron' on the first line:
const electron = require('electron');
Can I tell Visual Studio to launch the Electron app first before starting it's node.js debugger? Has anyone else gotten this set up to work at all?
This is possible. Try doing what's below:
Create a blank Node.js JavaScript console app in Visual Studio. You need a recent version of node installed I think: I have 12.18.3. I'm using VS 2019 Community.
Add a dependencies section to the package.json that's created and reference electron. I referenced 11.0.1 as below:
"dependencies": { "electron": "11.0.1" },
This puts an entry in Solution Explorer under npm, so to actually install it you can right-click/install npm package (or fire up a command prompt and do npm install).
Copy the code from the electron-quick-start on GitHub: create index.html AND preload.js files in your Visual Studio project, and paste the code from GitHub into them. Also paste the quick start main.js contents into app.js. There's no need to rename it.
Go to properties of the console app project file. Where it says 'Node exe path:' put the path to electron.exe that was installed, which is in subfolder node_modules\electron\dist\electron.exe.
Put a breakpoint on the first line of createWindow in your app.js.
Start in debug. It should break at the breakpoint and if you continue it will show the basic electron app. This is an Electron window with a message in it: e.g. 'Hello World! We are using Node.js 12.18.3, Chromium 87.0.4280.60, and Electron 11.0.1.'
This is all well and good, but how useful it is depends on what you really want Visual Studio to do for you. It will only break on the main thread, although you can debug the renderer threads using the Chrome dev tools as usual. I find the node tools apps a little limiting. Maybe one of the other project types would be better.
This answer was updated November 2020, and previous answers removed. Note that as usual in npm world things do tend to break over time: please make a comment if things aren't working for you.