javascript - 找不到模块 : Can't resolve 'child_process' NextJS + Nightmare

标签 javascript web-scraping next.js puppeteer nightmare

我正在尝试使用 Next JS + Nightmare Scraper 编译一个简单的示例。但是,当我尝试访问该页面时,我收到以下错误,并且该页面无法加载。

PS C:\Users\lucas\Documents\Projects\ProjectTest\pages\nightmare> npm run dev

Test@1.0.0 dev C:\Users\lucas\Documents\Projects\ProjectTest next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000

event - compiled successfully

event - build page: / wait - compiling... error - ./node_modules/nightmare/lib/nightmare.js:17:0

Module not found: Can't resolve 'child_process' null

Could not find files for / in .next/build-manifest.json

Could not find files for / in .next/build-manifest.json

Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp'


当我使用 node ./index.js 运行时,它工作正常。
使用 nightmare 或 puppeteer 会发生相同的错误。
index.js
const test = require('nightmare');

function Page() {

    return <div>Test 2</div>
}

export default Page
包.json
{
  "name": "Test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next dev"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "nightmare": "^3.0.2",
    "next": "^10.0.6",
    "puppeteer": "^7.1.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {}
}

最佳答案

发生错误是因为当 nightmare代码(期望在 Node.js 环境中运行)在客户端上运行 child_process不存在。您可以添加一个条件以确保它仅在服务器上运行。

if (typeof window === 'undefined') {
    const test = require('nightmare');
}
但是,我不确定您为什么要在页面中运行它。它并不意味着在浏览器中运行。

关于javascript - 找不到模块 : Can't resolve 'child_process' NextJS + Nightmare,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66198156/

相关文章:

javascript - Ajax - 如何在成功函数中使用返回的数组

python - 尝试使用 Scrapy 抓取 LinkedIn 时出现 999 响应

mongodb - 在 'next build' 期间 ECONNREFUSED 。与 'next dev' 配合使用

javascript - 从本地 json 文件创建动态路由 nextjs 13

javascript - -0.5 到 0.5 之间的随机数,高效

javascript - Node : smart JSON conversion to Excel file

javascript - MVC 5 中的搜索参数

python - 我需要帮助网络抓取

html - 当按钮没有关联的 "name"时,使用 Excel VBA 单击 Internet Explorer 中的按钮

reactjs - NextJS getStaticProps 没有被调用