如何在WSL环境上发开Electron应用

尝试开发Electron应用,搭建开发环境期间踩坑不少,对此做一总结,使用的各种环境为:操作系统:Windows10上的WSL1(Ubuntu-22.04)。

首先来到Electron的“快速入门”页面:点我传送

image

首先安装Node.js

传送链接就在Electron文档上面
image
这儿我选择的Node.js,on以及using分别是:v20.16.0(LTS),Linux以及nvm。
根据上面的选择,执行生成的安装脚本。

1
2
3
4
5
6
7
8
9
10
11
# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 20

# verifies the right Node.js version is in the environment
node -v # should print `v20.16.0`

# verifies the right npm version is in the environment
npm -v # should print `10.8.1`

初始化项目

按照以上的文档说明开始搭建项目,首先创建项目文件夹,并初始化项目:

1
2
mkdir my-electron-app && cd my-electron-app
npm init

然后很根据初始化时填写的信息生成package.json文件:

1
2
3
4
5
6
7
8
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "Hello World!",
"main": "main.js",
"author": "Jane Doe",
"license": "MIT"
}

安装Electron

截至到这儿都很成功,顺滑之际,立马就翻车了。
按照官方文档直接通过npm安装Electron:
npm install --save-dev electron
结果国内网络情况在这儿开始踩坑,安装半天装不上,并且会报网络错误。
这儿整理出我的解决办法:

1
2
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install --save-dev electron

这样就成功安装了Electron。

运行项目

首先是按照Eletron的文档创建项目文件:main.js,index.html,preload.js。
然后运行项目:
npm start
结果就又翻车了,报了一下错误:

1
node_modules/.store/electron@31.3.1/node_modules/electron/dist/electron: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory

通过查找资料得知,出现这一问题的原因是WSL中运行这一个几乎完整的Linux发行版,所以当Electron运行在WSL中时,他声明自己是在Linux之中,但是截至 2021 年 2 月,还没有开箱即用的支持运行为 Linux 编译的图形应用程序。简单地尝试运行您在 WSL 中安装了依赖项的开发中的 Electron 应用程序将尝试查找 X11 服务器,并因此无法启动。
解决办法是:

1
2
3
4
5
6
7
8
9
10
11
# If node_modules exists already that was installed in WSL:

rm -r node_modules

# then:

npm install --platform=win32

# or:

npm_config_platform=win32 npm install

但根据Electron Forge的官方文档说法,Electron Forge 的一些依赖项无法与 WSL 很好地配合使用,因为它们无法检测到它们是在 WSL 中运行的 (而不是 Linux),因此尝试在… Wine 中运行作为 Windows 可执行文件提供的某些工具。我们正在积极努力使依赖工具支持 WSL。解决方法是在 WSL 之外运行打包/制作/发布。