如何使npm软件包可作为电子应用程序的命令使用

问题描述

在开发电子应用程序时我面临一个奇怪的问题。我要实现的目标是使用lighthouse进行页面审核。我正在像这样以编程方式使用它

const command = `lighthouse ${website} --quiet --chrome-flags=--headless --output-path=${outputPath}   --output html --emulated-form-factor=${strategy}  --only-categories=${options}`;

os.execCommand(command,function() {
      res.send(response);
});

它的作用是在主线程(nodejs)中将lighthouse作为命令执行。我已经提到lighthousepackage.json中的依赖项,它在development模式下可以很好地工作。

奇怪的是,创建软件包时,它给了我一个错误lighthouse is not a recognized command

如何解决这种依赖性?或从node_modules>

提供命令路径

请指导。 PS:无法使用require将lighthouse用作模块。这也是一个内部托管此服务的独立应用程序。

解决方法

您可以将lighthouse安装为全局依赖项。如果您不想这样做,请使用npm bin来获取npm将在其中安装可执行文件的文件夹。然后,使用灯塔的绝对路径。 https://stackoverflow.com/a/15157360/10674906解释了如何做得更好。

,

您可以启动一个子进程并通过npx运行灯塔吗 允许npx解决依赖关系空间,而不是依靠os

const {app,BrowserWindow} = require('electron')
const childproc = require('child_process')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,height: 600,webPreferences: {
      preload: path.join(__dirname,'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  mainWindow.webContents.openDevTools()
}


app.whenReady().then(() => {
  createWindow()
  
  app.on('activate',function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed',function () {
  if (process.platform !== 'darwin') app.quit()
})

const child = childproc.spawn(
  'npx',[
    'lighthouse',`${website}`,`--quiet`,`--chrome-flags=--headless`,`--output-path=${outputPath}`,`--output`,`html`,`--emulated-form-factor=${strategy}`,`--only-categories=${options}`
  ],)

child.on('exit',function (code,signal) {
  console.log(
    'child process exited with ' + `code ${code} and signal ${signal}`
  )
})

child.on('error',(err) => {
  console.log(err)
})


child.stdout.on('data',(data) => {
  console.log(data.toString())
})

child.stderr.on('data',(data) => {
  console.error(`child stderr:\n${data}`)
})

不太确定您的整个设置,而是使用启动程序构建了这个示例,并在本地运行了灯塔...

$ npm start

> electron-quick-start@1.0.0 start 
> electron .

child stderr:
Please provide a url

child stderr:

Specify --help for available options

child process exited with code 1 and signal null