Webpack - ReferenceError:global is not defined,in next13

wgmfuz8q  于 2023-11-19  发布在  Webpack
关注(0)|答案(1)|浏览(230)

在开发NextJS 13应用程序时,我遇到了这个错误:ReferenceError: global is not defined
我搜索了错误并找到了一些解决方案,但它们不起作用。我试图更改配置文件,并试图跟踪错误,但这些都对我无效。
这是我的NextJS配置文件

  1. const nextConfig = {
  2. reactStrictMode: true,
  3. pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'mdx'],
  4. experimental: {
  5. appDir: true,
  6. mdxRs: true,
  7. },
  8. sassOptions: {
  9. prependData: `
  10. @import "styles/theme.scss";
  11. @import "styles/mixins.scss";
  12. `,
  13. },
  14. webpack: (config, {isServer}, options) => {
  15. config.module.rules.push(
  16. {
  17. test: /\.mdx?$/,
  18. use: [
  19. {
  20. loader: '@mdx-js/loader',
  21. /** @type {import('@mdx-js/loader').Options} */
  22. options: {...options},
  23. },
  24. ],
  25. },
  26. {
  27. test: /\.ya?ml$/,
  28. oneOf: [
  29. {
  30. resourceQuery: /stream/,
  31. options: {asStream: true},
  32. loader: 'yaml-loader',
  33. },
  34. {loader: 'yaml-loader'},
  35. ],
  36. }
  37. );
  38. if (!isServer) {
  39. config.resolve.fallback = {
  40. fs: false,
  41. };
  42. }
  43. config.infrastructureLogging = {
  44. level: 'error',
  45. };
  46. return config;
  47. },
  48. async redirects() {
  49. return [
  50. {
  51. source: '/',
  52. destination: '/home',
  53. permanent: true,
  54. },
  55. ];
  56. },
  57. };

字符串
错误代码:

编辑

我发现这个错误是由于从utils目录中导入函数而引起的,我把我的工具函数放在了utils目录中,并在客户端组件中使用它们。现在的问题是,我不能把'use client'放在我的工具函数文件中,这也会导致服务器端组件中的错误。我试图为工具函数创建两个文件,一个用于客户端,另一个用于服务器端,但这也不起作用。
对于这个问题,有没有更好、更直观的解决方案?

vd2z7a6w

vd2z7a6w1#

我猜你也使用turborepo。Prisma有这个指南,使用globalThis。基本上这个想法类似于使用global,但是因为global只在node环境中可用,我们必须使用globalThis代替。

  1. import { PrismaClient } from '@prisma/client'
  2. const prismaClientSingleton = () => {
  3. return new PrismaClient()
  4. }
  5. type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>
  6. const globalForPrisma = globalThis as unknown as {
  7. prisma: PrismaClientSingleton | undefined
  8. }
  9. const prisma = globalForPrisma.prisma ?? prismaClientSingleton()
  10. if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
  11. export default prisma

字符串
来源:https://www.prisma.io/docs/guides/other/troubleshooting-orm/help-articles/nextjs-prisma-client-dev-practices

展开查看全部

相关问题