如何在运行“pkg。”时解决“Error: Cannot find module 'puppeteer'”问题

3
所以我有一个 Puppeteer 脚本,我想将它制作成一个 .exe 文件,并且在该文件内包含 node_modules。

index.js:

const fs = require("fs");
const puppeteer = require("puppeteer-extra");

const StealthPlugin = require("puppeteer-extra-plugin-stealth");
puppeteer.use(StealthPlugin());

code...

当我运行pkg .时,它会创建.exe文件,但我必须在node_modules文件夹旁边运行它才能避免出现错误"Error: Cannot find module 'puppeteer'"
我也尝试过在我的package.json中这样做。
  "pkg": {
    "assets": "node_modules/**/*.*"
  },

但是已经过去了一个小时左右,什么也没有创建,就像它已经冻结了。

有人可以帮忙吗?非常感谢!

1个回答

2
const puppeteer = require("puppeteer-extra");
const isPkg = typeof process.pkg !== 'undefined';

const chromiumExecutablePath = isPkg 
    ? puppeteer.executablePath().replace(
        /^.*?\/node_modules\/puppeteer\/\.local-chromium/,
        path.join(path.dirname(process.execPath), '.local-chromium')
      ) : puppeteer.executablePath()
);
const browser = await puppeteer.launch({
   executablePath: chromiumExecutablePath,
   args: [
     "--start-maximized",
     "--no-sandbox",
   ],
   headless: false,
   defaultViewport: null
})

要构建,请使用npm脚本,例如:

"build": "pkg src/index.js --public --targets node14-win-x64 --out-path dist"

我遇到了一个错误:“无法启动浏览器进程”,并且它找不到.local-chromium文件夹中的chrome.exe文件。 - Mike
具体地说:错误:无法启动浏览器进程!spawn /snapshot/FT Auto Login Bot #2/node_modules/puppeteer-core/.local-chromium/mac-1045629/chrome-mac/Chromium.app/Contents/MacOS/Chromium ENOENT - Mike
@Mike 尝试使用参数:["--no-sandbox", "--start-maximized"] - Vasil Gerginski
什么是 process.pkg?它说“在类型 'Process' 上不存在属性 'pkg'”。 - Hanh Nguyen
@Mike 我也遇到了同样的错误,你解决了吗? - Hanh Nguyen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接