有一个解决方案。绝对不稳定且未经测试,请自行承担风险。而且,如果您能找到并修复作为副作用出现的错误,请随时分享它们:)
我们将使用一个名为pkg 的模块将脚本与node 捆绑在一起。同样为简单起见,我们将使用npx。
有一些副作用,但这是第一次使用 electron 和 nightmare。
考虑以下脚本,
const Nightmare = require("nightmare");
const nightmare = Nightmare({
show: true
});
nightmare
.goto("https://example.com")
.title()
.end()
.then(console.log)
.catch(error => {
console.error(error);
});
这是一个简单的脚本,上面写着,转到example.com 并给我标题。
酷!让我们尝试通过npx 和pkg 使用它。代码是,
npx pkg app.js --target 'host'
但是,我们遇到了一些严重的错误,
> Warning Cannot include file %1 into executable.
The file must be distributed with executable as %2.
node_modules/nightmare/lib/runner.js
path-to-executable/nightmare/runner.js
> Warning Cannot include file %1 into executable.
The file must be distributed with executable as %2.
node_modules/nightmare/lib/frame-manager.js
...
等等等等,文件不会运行。
Error: spawn /home/someone/Desktop/a/electron/dist/electron ENOENT
找不到所需的文件,因为它们没有捆绑在一起。我们将使用process.cwd() 来获取驻留在相关文件夹中的那些数据。
const nodeDir = process.cwd() + "/node_modules/"; // <- Get node modules folder
const nightmareDir = nodeDir + "nightmare"; // <-- Get nightmarejs path
const electronDir = nodeDir + "electron"; // <-- Get electron path
const Nightmare = require(nightmareDir);
const electronPath = require(electronDir);
const nightmare = Nightmare({
show: true,
electronPath // <-- use the specific electron path
});
nightmare
.goto("https://example.com")
.title()
.end()
.then(console.log)
.catch(error => {
console.error(error);
});
当我运行它时,它向我显示了更多警告,但那是因为我还没有优化 process.cwd()。然后我运行它,瞧!
➜ a npx pkg app.js --target 'host'
> pkg@4.3.1
> Warning Cannot resolve 'nightmareDir'
/home/someone/Desktop/a/app.js
Dynamic require may fail at run time, because the requested file
is unknown at compilation time and not included into executable.
Use a string literal as an argument for 'require', or leave it
as is and specify the resolved file name in 'scripts' option.
> Warning Cannot resolve 'electronDir'
/home/someone/Desktop/a/app.js
Dynamic require may fail at run time, because the requested file
is unknown at compilation time and not included into executable.
Use a string literal as an argument for 'require', or leave it
as is and specify the resolved file name in 'scripts' option.
➜ a ./app
Example Domain // <-- Our sweet result :D
➜ a
这可以改进和调整,但我会把它留给你。