Electron/Angular示例应用中出现TypeError: window.require is not a function错误的求助
Hey there! As someone who’s worked through Angular + Electron setup hurdles before, let’s get your app out of that blank window funk. That window.require error is super common with newer Electron versions (like your v12.0.1) because of default security changes—here’s how to fix it step by step:
1. Update BrowserWindow Web Preferences (Critical for Electron 12+)
Electron 12+ enables contextIsolation by default, which blocks direct access to Node.js APIs from the renderer process (your Angular app). Just setting nodeIntegration: true isn’t enough anymore—you need to disable context isolation too.
Open your Electron main file (usually main.ts or main.js) and update the BrowserWindow constructor options:
const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, // This is the missing piece for Electron 12+ enableRemoteModule: true // Add this if you plan to use remote modules later } });
Save the file, then restart your Electron process after making this change.
2. Verify Angular Build & Electron Load Path
Sometimes the blank window happens because Electron can’t find your compiled Angular files. Double-check these details:
- In
angular.json, confirm theoutputPathis set to something likedist/your-app-name - In your Electron main file, ensure you’re loading the correct path to
index.html:// If using a compiled Angular build mainWindow.loadFile('dist/your-app-name/index.html'); // If running Angular in dev mode (e.g., ng serve) mainWindow.loadURL('http://localhost:4200');
3. Safe-Guard window.require Calls in Angular
To avoid this error popping up when running your Angular app in a regular browser (not Electron), wrap your require calls in an environment check:
// First, declare the window extension for TypeScript declare global { interface Window { require: any; } } // Then in your component/service: if (window.require) { const electron = window.require('electron'); // Use Electron APIs here (e.g., ipcRenderer, shell) }
This ensures the code only tries to access window.require when it’s available in the Electron context.
4. Double-Check Dependency Compatibility
Since you’re using Node v10.19.0 and Electron v12.0.1, make sure your dependencies are compatible. Run npm install again to fix any corrupted packages, and confirm that your @angular/cli version (Angular 9+ works best with Electron 12) plays nice with your Electron setup.
After making these changes, stop any running processes, run npm run build (if using a compiled build) followed by npm run electron, and your app should load properly without the blank window or require error.
内容的提问来源于stack exchange,提问作者Wolfeur

