Electron+Angular项目导入os模块提示找不到模块该如何解决?
修复步骤
1. 先解决TypeScript类型报错
你安装了@types/node但没有在TS配置中声明引用,所以找不到类型,打开项目下的tsconfig.app.json(Angular项目优先改这个,没有就改根目录tsconfig.json),在compilerOptions中增加如下配置:
{ "compilerOptions": { // 保留你的原有配置,只新增下面两行 "types": ["node"], "typeRoots": ["node_modules/@types"] } }
2. 处理Electron环境的Node能力调用
Electron默认关闭渲染进程的Node.js权限,有两种可选方案:
方案A:快速适配(不推荐,有安全风险)
直接开启渲染进程的Node集成,在主进程创建窗口的代码中修改webPreferences配置:
const mainWindow = new BrowserWindow({ // 你的原有窗口尺寸等配置 webPreferences: { nodeIntegration: true, contextIsolation: false, // 保留原有其他配置 } })
同时需要修改angular.json中对应项目的构建配置,避免Angular打包时过滤Node原生模块:
{ "projects": { "你的项目名": { "architect": { "build": { "options": { // 保留原有配置,新增下面两项 "allowedCommonJsDependencies": ["os"], "externalDependencies": ["os"] } } } } } }
改完后你原来的Angular代码就可以正常运行。
方案B:安全适配(推荐,符合Electron官方安全规范)
不要直接在渲染层调用Node模块,通过preload脚本把你需要的能力暴露给前端:
- 新建preload.js文件,写入如下内容:
const os = require('os') const { contextBridge } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { getHostname: () => os.hostname() })
- 主进程创建窗口时配置preload路径,保持安全配置默认开启:
const mainWindow = new BrowserWindow({ // 原有窗口配置 webPreferences: { preload: path.join(__dirname, 'preload.js'), // 替换为你preload文件的实际路径 contextIsolation: true, nodeIntegration: false } })
- 修改你的Angular代码,直接调用暴露的方法即可,不需要再引入os模块:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor() { } ngOnInit(): void { console.log(window.electronAPI.getHostname()); } }
如果TypeScript报window上不存在electronAPI的错误,在src目录下新建typings.d.ts文件,添加全局类型声明:
declare interface Window { electronAPI: { getHostname: () => string } }
内容的提问来源于stack exchange,提问作者Carloshf
相关产品推荐
相关产品推荐

