Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS cannot find __dirname

Tags:

next.js

I have a build error with a solito.dev, NextJS + Expo application. Originally, it ran fine.

Here is what happened:

  1. I got a new computer, Mac M2 chip, and pulled this repository from GitHub
  2. nextJS app works find using yarn && yarn web-dev
  3. I built the expo app, npx expo prebuild, and npx pod-install, but ran into errors.
  4. To solve these errors, I used things like sudo pod install --allow-root Sudo npx expo prebuild
  5. I also tried some other stuff, like setting up arch -x86_64 and installing rosetta2.
  6. I am not sure what combination worked, but eventually the Expo app worked.
  7. Then the nextJS app no longer works
sudo yarn web
Password:
   ▲ Next.js 14.0.3
   - Local:        http://localhost:3000

 ⚠ Invalid next.config.js options detected: 
 ✓ Ready in 3.1s

While the error says it is in the next.config.js, I don't think it is. Because I didn't modify the next.config.js file. Anyway though, here is the next.config.js file:

// This file sets a custom webpack configuration to use your Next.js app
// with Sentry.
// https://nextjs.org/docs/api-reference/next.config.js/introduction
// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
const { withExpo } = require('@expo/next-adapter')
const { withSentryConfig } = require('@sentry/nextjs')
const withFonts = require('next-fonts')
const withPWA = require('next-pwa')({
  dest: 'public',
  disable: process.env.NODE_ENV === 'development',
  register: true,
  skipWaiting: false,
})
const withPlugins = require('next-compose-plugins')
//
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  webpack: (config) => {
    config.experiments = {
      ...config.experiments,
      topLevelAwait: true,
      layers: true,
    }
    config.resolve = {
      ...config.resolve,
      alias: {
        ...config.resolve.alias,
        'react-native$': 'react-native-web',
      },
    }
    return config
  },

  transpilePackages: [
    //transpile packages here, eliminated for brevity
  ],
  images: {
    formats: ['image/avif', 'image/webp'],
    domains: [
//domains here, eliminated for brevity
    ],
  },
}

const APP_ENV = process.env.APP_ENV || 'release'

require('dotenv').config({
  path: `../../.env`,
})

const env = {}

Object.keys(process.env).forEach((key) => {
  if (key.startsWith('NEXT_PUBLIC_')) {
    env[key] = process.env[key]
  }
})

module.exports = //withSentryConfig(
  withPlugins(
    [
      withFonts({
        projectRoot: __dirname,
      }),
      [
        withPWA,
        {
          projectRoot: __dirname,
        },
      ],
      [withExpo], // MAKE SURE THIS GOES LAST!
    ],
    {
      ...nextConfig,
      env,
      // redirects: async () => {
      //   return [
      //     {
      //       source: '/',
      //       destination: 'https://www.biz.karmatrade.com/',
      //       permanent: true,
      //     },
      //   ]
      // },
      async rewrites() {
        return [
          {
            source: '/@:spaceid',
            destination: '/space/:spaceid',
          },
          {
            source: '/m/@:marketid',
            destination: '/market/:marketid',
          },
        ]
      },
    }
  ) /*,
  { silent: true,  },
  { hideSourceMaps: true }
)*/

/*
withPlugins(
    [
      [withFonts, { projectRoot: __dirname }],
      [withPWA, { projectRoot: __dirname }],
    ],
*/

yarn web gives a permissions error, so I am using sudo yarn web, even though I didn't need to do that before. Not sure how to override this.

yarn web
   ▲ Next.js 14.0.3
   - Local:        http://localhost:3000

 ⚠ Invalid next.config.js options detected: 
 ⚠     Unrecognized key(s) in object: 'projectRoot'
 ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config
[Error: EACCES: permission denied, unlink '/Users/monafang/Documents/GitHub/karma-trade-platform/apps/next/.next/server/middleware-build-manifest.js'] {
  errno: -13,
  code: 'EACCES',
  syscall: 'unlink',
  path: '/Users/monafang/Documents/GitHub/karma-trade-platform/apps/next/.next/server/middleware-build-manifest.js'
}
like image 823
mfang Avatar asked Aug 02 '26 14:08

mfang


2 Answers

The __dirname variable is not defined in Next.js because it is not a Node.js environment. Next.js is a React framework that runs on top of Node.js, but it has its own runtime environment.

If you need to access the directory name of a file in Next.js, you can use the path module. For example, the following code will print the directory name of the file that is currently being executed:

import path from 'path';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

console.log(__dirname);

You can also use the process.cwd() function to get the current working directory.

If you are getting a ReferenceError: __dirname is not defined error, it means that you are trying to use the __dirname variable in a context where it is not defined. This can happen if you are using a Babel plugin or other tool that transpiles your code to ES6 modules.

To fix this error, you can either remove the Babel plugin or use a different tool that does not transpile your code to ES6 modules. You can also use the workaround described above to get the directory name of a file in Next.js.

like image 87
Shivo'ham 0 Avatar answered Aug 05 '26 13:08

Shivo'ham 0


Use can use below codes:

import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
console.log(__dirname);

Here are the full codes for next.config.mjs:

import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
console.log(__dirname);
const nextConfig = {
  reactStrictMode: false,
  transpilePackages: [
    "antd",
    "rc-util",
    "@babel/runtime",
    "@ant-design/icons",
    "@ant-design/icons-svg",
    "rc-pagination",
    "rc-picker",
    "rc-tree",
    "rc-table",
  ],
  images: {
    domains: ["website.com", "localhost:3010", "localhost"],
  },
  webpack: (config) => {
    config.resolve.alias["@"] = path.resolve(__dirname, "src");
    return config;
  },
};

export default nextConfig;
like image 40
Shubham Verma Avatar answered Aug 05 '26 12:08

Shubham Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!