how to install app without root

本文探讨了在没有root权限的情况下,在Linux系统上安装Vim编辑器的方法。针对受限环境,提供了一系列实用的技巧和替代方案,帮助用户克服权限限制,实现Vim的顺利安装。
构建您的第一个应用程序 按照教程进行作 这是 Electron 教程的第 2 部分。 先决条件 构建您的第一个应用程序 使用预加载脚本 添加功能 打包您的应用程序 发布和更新 学习目标 在本教程的这一部分中,您将学习如何设置 Electron 项目 并编写一个最小的入门应用程序。在本节结束时, 您应该能够在开发模式下运行一个有效的 Electron 应用程序,来自 您的终端。 设置项目 避免 WSL 如果您使用的是 Windows 计算机,请不要使用适用于 Linux 的 Windows 子系统 (WSL) 在遵循本教程时,因为您在尝试执行 应用。 初始化 npm 项目 电子应用程序使用 npm 搭建脚手架,文件为 package.json 作为切入点。首先创建一个文件夹并初始化一个 npm 包 在其中有 .npm init npm 纱 mkdir my-electron-app && cd my-electron-app npm init 此命令将提示您在package.json中配置一些字段。 出于本教程的目的,需要遵循一些规则: 入口点应该是(你很快就会创建该文件)。main.js author、license 和 description 可以是任何值,但以后打包时将是必需的。 使用常规文件夹安装依赖项node_modules Electron 的打包工具链要求文件夹物理位于磁盘上,在 npm 安装节点依赖项的方式。默认情况下,Yarn Berry 和 pnpm 都使用替代安装策略。node_modules 因此,如果您使用 那些包管理器。 然后,将 Electron 安装到应用程序的 devDependencies 中,这是外部 生产中不需要仅开发包依赖项。 为什么 Electron 是开发依赖项? 这似乎有悖常理,因为你的生产代码正在运行 Electron API。在引擎盖下, Electron 的 JavaScript API 绑定到包含其实现的二进制文件。包装步骤 Electron 处理此二进制文件的捆绑,无需将其指定为生产 屬地。 npm 纱 npm install electron --save-dev 警告 为了正确安装 Electron,您需要确保其生命周期 脚本能够运行。这意味着避免在 npm 上使用标志,并允许列入在其他包管理器上运行构建脚本的权限。postinstall--ignore-scriptselectron 这可能会在 Electron 的未来版本中改变。有关更多详细信息,请参阅 electron/rfcs#22。 初始化包后,您的package.json文件应该如下所示 并安装 Electron。您现在还应该有一个文件夹,其中包含 Electron 可执行文件,以及指定 要安装的确切依赖项版本。node_modulespackage-lock.json package.json { "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Jane Doe", "license": "MIT", "devDependencies": { "electron": "23.1.3" } } 高级 Electron 安装步骤 如果直接安装 Electron 失败,请参阅我们的高级安装文档,了解有关下载镜像、代理和故障排除步骤的说明。 添加 .gitignore .gitignore 文件指定要避免跟踪的文件和目录与 Git。您应该将 GitHub 的 Node.js gitignore 模板的副本放入项目的根文件夹中,以避免提交项目的文件夹。node_modules 运行 Electron 应用程序 进一步阅读 阅读 Electron 的流程模型文档以更好地了解 Electron 的多个流程如何协同工作。 您在 package.json 中定义的主脚本是任何Electron 应用程序的入口点。该脚本控制主进程,该进程在Node.js环境中运行,负责控制应用程序的生命周期、显示本机接口、执行特权作以及管理渲染器进程(稍后会详细介绍)。 在创建您的第一个 Electron 应用程序之前,您将首先使用一个简单的脚本来确保您的main 进程入口点配置正确。在根文件夹中创建一个文件使用一行代码:main.js main.js console.log(&#39;Hello from Electron 👋&#39;) 因为 Electron 的主进程是一个Node.js运行时,所以你可以执行任意的Node.js代码(你甚至可以把它用作 REPL)。要执行这个脚本,add 到你package.json的 scripts 字段中的命令。这个命令会告诉 Electron 可执行文件在当前目录中查找主script 并在开发模式下运行它。electronelectron .start package.json { "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "main.js", "scripts": { "start": "electron .", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Jane Doe", "license": "MIT", "devDependencies": { "electron": "23.1.3" } } npm Yarn npm run start Your terminal should print out . Congratulations, you have executed your first line of code in Electron! Next, you will learn how to create user interfaces with HTML and load that into a native window.Hello from Electron 👋 Loading a web page into a BrowserWindow In Electron, each window displays a web page that can be loaded either from a local HTML file or a remote web address. For this example, you will be loading in a local file. Start by creating a barebones web page in an file in the root folder of your project:index.html index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src &#39;self&#39;; script-src &#39;self&#39;" /> <meta http-equiv="X-Content-Security-Policy" content="default-src &#39;self&#39;; script-src &#39;self&#39;" /> <title>Hello from Electron renderer!</title> </head> <body> <h1>Hello from Electron renderer!</h1> <p>👋</p> </body> </html> Now that you have a web page, you can load it into an Electron BrowserWindow. Replace the contents of your file with the following code. We will explain each highlighted block separately.main.js main.js const { app, BrowserWindow } = require(&#39;electron&#39;) const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile(&#39;index.html&#39;) } app.whenReady().then(() => { createWindow() }) Importing modules main.js (Line 1) const { app, BrowserWindow } = require(&#39;electron&#39;) In the first line, we are importing two Electron modules with CommonJS module syntax: app, which controls your application&#39;s event lifecycle. BrowserWindow, which creates and manages app windows. Module capitalization conventions Typed import aliases ES Modules in Electron ECMAScript modules (i.e. using to load a module) are supported in Electron as of Electron 28. You can find more information about the state of ESM in Electron and how to use them in our app in our ESM guide.import Writing a reusable function to instantiate windows The function loads your web page into a new BrowserWindow instance:createWindow() main.js (Lines 3-10) const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile(&#39;index.html&#39;) } Calling your function when the app is ready main.js (Lines 12-14) app.whenReady().then(() => { createWindow() }) Many of Electron&#39;s core modules are Node.js event emitters that adhere to Node&#39;s asynchronous event-driven architecture. The app module is one of these emitters. In Electron, BrowserWindows can only be created after the app module&#39;s ready event is fired. You can wait for this event by using the app.whenReady() API and calling once its promise is fulfilled.createWindow() info You typically listen to Node.js events by using an emitter&#39;s function..on + app.on(&#39;ready&#39;, () => { - app.whenReady().then(() => { createWindow() }) However, Electron exposes as a helper specifically for the event to avoid subtle pitfalls with directly listening to that event in particular. See electron/electron#21972 for details.app.whenReady()ready At this point, running your Electron application&#39;s command should successfully open a window that displays your web page!start Each web page your app displays in a window will run in a separate process called a renderer process (or simply renderer for short). Renderer processes have access to the same JavaScript APIs and tooling you use for typical front-end web development, such as using webpack to bundle and minify your code or React to build your user interfaces. Managing your app&#39;s window lifecycle Application windows behave differently on each operating system. Rather than enforce these conventions by default, Electron gives you the choice to implement them in your app code if you wish to follow them. You can implement basic window conventions by listening for events emitted by the app and BrowserWindow modules. Process-specific control flow Checking against Node&#39;s process.platform variable can help you to run code conditionally on certain platforms. Note that there are only three possible platforms that Electron can run in: (Windows), (Linux), and (macOS).win32linuxdarwin Quit the app when all windows are closed (Windows & Linux) On Windows and Linux, closing all windows will generally quit an application entirely. To implement this pattern in your Electron app, listen for the app module&#39;s window-all-closed event, and call app.quit() to exit your app if the user is not on macOS. app.on(&#39;window-all-closed&#39;, () => { if (process.platform !== &#39;darwin&#39;) app.quit() }) Open a window if none are open (macOS) In contrast, macOS apps generally continue running even without any windows open. Activating the app when no windows are available should open a new one. To implement this feature, listen for the app module&#39;s activate event, and call your existing method if no BrowserWindows are open.createWindow() Because windows cannot be created before the event, you should only listen for events after your app is initialized. Do this by only listening for activate events inside your existing callback.readyactivatewhenReady() app.whenReady().then(() => { createWindow() app.on(&#39;activate&#39;, () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) Final starter code docs/fiddles/tutorial-first-app (39.0.0) main.js index.html const { app, BrowserWindow } = require(&#39;electron/main&#39;) const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 }) win.loadFile(&#39;index.html&#39;) } app.whenReady().then(() => { createWindow() app.on(&#39;activate&#39;, () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on(&#39;window-all-closed&#39;, () => { if (process.platform !== &#39;darwin&#39;) { app.quit() } }) Optional: Debugging from VS Code If you want to debug your application using VS Code, you need to attach VS Code to both the main and renderer processes. Here is a sample configuration for you to run. Create a launch.json configuration in a new folder in your project:.vscode .vscode/launch.json { "version": "0.2.0", "compounds": [ { "name": "Main + renderer", "configurations": ["Main", "Renderer"], "stopAll": true } ], "configurations": [ { "name": "Renderer", "port": 9222, "request": "attach", "type": "chrome", "webRoot": "${workspaceFolder}" }, { "name": "Main", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron", "windows": { "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd" }, "args": [".", "--remote-debugging-port=9222"], "outputCapture": "std", "console": "integratedTerminal" } ] } The "Main + renderer" option will appear when you select "Run and Debug" from the sidebar, allowing you to set breakpoints and inspect all the variables among other things in both the main and renderer processes. What we have done in the file is to create 3 configurations:launch.json Main is used to start the main process and also expose port 9222 for remote debugging (). This is the port that we will use to attach the debugger for the . Because the main process is a Node.js process, the type is set to .--remote-debugging-port=9222Renderernode Renderer is used to debug the renderer process. Because the main process is the one that creates the process, we have to "attach" to it () instead of creating a new one. The renderer process is a web one, so the debugger we have to use is ."request": "attach"chrome Main + renderer is a compound task that executes the previous ones simultaneously. caution Because we are attaching to a process in , it is possible that the first lines of your code will be skipped as the debugger will not have had enough time to connect before they are being executed. You can work around this by refreshing the page or setting a timeout before executing the code in development mode.Renderer Further reading If you want to dig deeper in the debugging area, the following guides provide more information: Application Debugging DevTools Extensions 总结 电子应用程序是使用 npm 包设置的。应该安装 Electron 可执行文件 ,可以使用 package.json文件。devDependencies 可执行文件运行在package.json属性中找到的 JavaScript 入口点。 该文件控制 Electron 的主进程,该进程运行 Node.js 的实例,并且是 负责应用的生命周期,显示本机接口,执行特权作, 以及管理渲染器进程。main 渲染器进程(或简称渲染器)负责显示图形内容。您可以 通过将网页指向网址或本地 HTML 文件,将网页加载到渲染器中。 渲染器的行为与常规网页非常相似,并且可以访问相同的 Web API。 在本教程的下一节中,我们将学习如何使用 特权 API 以及如何在进程之间进行通信。 总结并为我写出完整的步骤
最新发布
11-01
以下是根据你提供的 Electron 教程内容,**完整、详细地总结出“构建你的第一个 Electron 应用程序”的全部步骤**。我们将从零开始一步步创建一个最小但可运行的 Electron 桌面应用,并附带解释和代码。 --- ## ✅ 目标 创建一个最简单的 Electron 应用: - 能在开发模式下启动 - 显示一个窗口 - 加载本地 HTML 页面 - 正确管理窗口生命周期(适配 macOS / Windows / Linux) - 可通过 `npm run start` 启动 --- ## 🧱 第一步:初始化项目结构 ### 1. 创建项目文件夹并进入 ```bash mkdir my-electron-app && cd my-electron-app ``` > 建议不要使用 WSL(Windows Subsystem for Linux)来运行 Electron 开发环境,可能会导致图形界面无法显示。 --- ### 2. 初始化 npm 项目 ```bash npm init -y ``` 这会生成一个默认的 `package.json` 文件。你可以手动编辑字段使其更规范: ```json { "name": "my-electron-app", "version": "1.0.0", "description": "Hello World!", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Your Name", "license": "MIT" } ``` --- ### 3. 安装 Electron 作为开发依赖 ```bash npm install electron --save-dev ``` > ⚠️ 注意:Electron 是 **devDependencies**,因为打包时工具链会自动包含其二进制文件,不需要发布到生产依赖中。 安装完成后,你应该能看到: - `node_modules/electron` 文件夹 - `package-lock.json` - `package.json` 中新增 `"electron": "^28.0.0"`(版本可能不同) --- ### 4. 添加 `.gitignore` 文件(推荐) 防止提交 `node_modules` 等不必要的文件。 ```bash # .gitignore node_modules/ dist/ out/ *.log .env.local ``` 或者参考 GitHub 官方模板:[https://github.com/github/gitignore/blob/main/Node.gitignore](https://github.com/github/gitignore/blob/main/Node.gitignore) --- ## 💻 第二步:编写主进程脚本(main.js) 这是 Electron 的入口文件,控制应用程序的主进程(Node.js 环境)。 ### 创建 `main.js` ```js // main.js const { app, BrowserWindow } = require(&#39;electron&#39;) // 创建主窗口函数 function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 防止 XSS,禁用 nodeIntegration 默认是安全做法 nodeIntegration: false, contextIsolation: true } }) // 加载本地 HTML 文件 win.loadFile(&#39;index.html&#39;) } // 当 Electron 完成初始化后执行 app.whenReady().then(() => { createWindow() // macOS 特性:点击 dock 图标重新打开窗口 app.on(&#39;activate&#39;, () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // 关闭所有窗口时退出应用(除了 macOS) app.on(&#39;window-all-closed&#39;, () => { if (process.platform !== &#39;darwin&#39;) { app.quit() } }) ``` ✅ 解释: - `app`: 控制整个应用的生命周期。 - `BrowserWindow`: 创建和管理原生窗口。 - `whenReady()`: Promise 形式等待 Electron 初始化完成。 - `window-all-closed`: 在非 macOS 上关闭所有窗口即退出程序。 - `activate`: macOS 下即使没有窗口也保持运行,点击图标应重新打开窗口。 --- ## 🌐 第三步:创建网页界面(index.html) Electron 使用 Chromium 渲染页面,所以每个窗口就是一个 Web 页面。 ### 创建 `index.html` ```html <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- 内容安全策略,提升安全性 --> <meta http-equiv="Content-Security-Policy" content="default-src &#39;self&#39;; script-src &#39;self&#39;"> <title>Hello from Electron!</title> </head> <body> <h1>Hello from Electron Renderer Process 👋</h1> <p>这是一个在渲染进程中运行的网页。</p> </body> </html> ``` 📌 提示: - 这个页面运行在 **渲染器进程(Renderer Process)**,类似浏览器标签页。 - 它可以使用前端技术栈(React/Vue/Webpack/Vite 等)进行增强。 --- ## ▶️ 第四步:添加启动命令 修改 `package.json` 中的 `scripts` 字段: ```json "scripts": { "start": "electron ." } ``` 现在你可以通过以下命令启动应用: ```bash npm run start ``` 🎯 成功标志: - 弹出一个 800×600 的窗口 - 显示 “Hello from Electron Renderer Process” - 支持跨平台窗口行为(macOS 不退出,Win/Linux 关闭即退出) --- ## 🔍 可选:VS Code 调试配置(launch.json) 如果你想调试主进程和渲染器进程,请创建 `.vscode/launch.json`: ```json // .vscode/launch.json { "version": "0.2.0", "compounds": [ { "name": "Main + Renderer", "configurations": ["Main", "Renderer"], "stopAll": true } ], "configurations": [ { "name": "Main", "type": "node", "request": "launch", "cwd": "${workspaceFolder}", "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron", "windows": { "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd" }, "args": [".", "--remote-debugging-port=9222"], "outputCapture": "std", "console": "integratedTerminal" }, { "name": "Renderer", "type": "chrome", "request": "attach", "port": 9222, "webRoot": "${workspaceFolder}" } ] } ``` 使用方式: 1. 打开 VS Code 2. 点击左侧「运行与调试」图标 3. 选择 `Main + Renderer` 并点击绿色三角运行 4. 可以在主进程和渲染器中设置断点调试 > ⚠️ 注意:由于连接延迟,首行代码可能跳过,建议加 `debugger` 或刷新页面。 --- ## 📦 最终项目结构 ``` my-electron-app/ ├── main.js # 主进程逻辑 ├── index.html # 渲染器页面 ├── package.json # 项目描述 & 脚本 ├── package-lock.json # 锁定依赖版本 ├── node_modules/ # 依赖库 └── .gitignore # 忽略文件(可选) └── .vscode/ # VS Code 配置(可选) └── launch.json ``` --- ## ✅ 总结:关键知识点回顾 | 概念 | 说明 | |------|------| | **主进程 (Main Process)** | Node.js 环境,负责创建窗口、调用系统 API、管理生命周期 | | **渲染器进程 (Renderer Process)** | 每个窗口独立运行的 Chromium 实例,用于展示 UI | | **BrowserWindow** | 创建桌面窗口的核心类 | | **app.whenReady()** | 推荐方式等待 Electron 初始化完毕 | | **跨平台窗口管理** | macOS 不关闭即退出;其他平台关闭所有窗口则退出 | | **HTML 页面加载** | 使用 `win.loadFile()` 加载本地 HTML | --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值