ModuleNotFoundError:未找到模块:错误:无法解析“ node_modules / mongodb / lib”中的“ dns”

时间:2020-11-08 15:01:42

标签: mongodb npm next.js node-mongodb-native

我的项目(NextJS)运行正常,突然我遇到了ModuleNotFoundError问题。尤其是在nextJs动态路由的情况下。

我的页面结构不起作用 页面/程序/ [程序类型] / [程序] .jsx

“ mongodb”:“ ^ 3.5.9”

ModuleNotFoundError: Module not found: Error: Can't resolve 'dns' in 'node_modules/mongodb/lib'

ModuleNotFoundError: Module not found: Error: Can't resolve 'dns' in '/project-path/node_modules/mongodb/lib'
    at /project-path/node_modules/webpack/lib/Compilation.js:925:10
    at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:401:22
    at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:130:21
    at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:224:22
    at /project-path/node_modules/neo-async/async.js:2830:7
    at /project-path/node_modules/neo-async/async.js:6877:13
    at /project-path/node_modules/webpack/lib/NormalModuleFactory.js:214:25
    at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:213:14
    at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/project-path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:13:1)
    at /project-path/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js:44:7
    at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/project-path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:13:1)
    at /project-path/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/project-path/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:25:1)
    at /project-path/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:67:43

2 个答案:

答案 0 :(得分:1)

这是nextjs中服务器端代码的真正细微问题。

错误很明显:您正在尝试在客户端代码中执行服务器端代码(mongo查询)。原因不明显,因为我确定您没有错误的代码...

经过一些调试后,我发现如果导入mongo代码而不使用它,则会引发此错误。 请参见下文,了解如何避免这种情况

好的和坏的例子

所以,这很好:

import { findUsers } from '../lib/queries'

function Home({ users }) {
  return (
    <h1>Users list</h1>
    //users.map and so on...
  )
}

export async function getServerSideProps() {
  const users = await findUsers()
  return {
    props: {
      users: users
    }
  }
}

export default Home

这将引发错误:

import { findUsers } from '../lib/queries'

function Home({ users }) {
  return (
    <h1>Users list</h1>
    //users.map and so on...
  )
}

export async function getServerSideProps() {
  // call disabled to show the error
  // const users = await findUsers()
  return {
    props: {
      users: [] //returned an empty array to avoid other errors
    }
  }
}

export default Home

如何避免

为避免此错误,只需删除在组件中导入的服务器端代码,如果不使用,请在getServerSideProps中。

答案 1 :(得分:0)

将您的服务器端编码模块(例如:模型、数据库连接器)保留在 Page 目录之外。

供参考:https://nextjs.org/docs/messages/prerender-error