Home > database >  Next.js: _app file being bypassed
Next.js: _app file being bypassed

Time:09-16

I'm busy making a web app using Next.js as a framework. I want to create a custom _app component to wrap the pages, but it seems that it's being completely bypassed.

My _app.tsx file looks like this:

import type { AppProps } from "next/app";
import { Fragment } from "react";

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Fragment>
      <div>Hello world</div>
      <Component {...pageProps} />
    </Fragment>
  );
}

I added the div above the component just to test if it would appear. Importing global styles also does nothing.

My next.config.js looks like this:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
}

module.exports = nextConfig

And my package.json like this:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "12.3.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "sass": "^1.54.9"
  },
  "devDependencies": {
    "@types/node": "18.7.16",
    "@types/react": "18.0.19",
    "@types/react-dom": "18.0.6",
    "eslint": "8.23.0",
    "eslint-config-next": "12.3.0",
    "typescript": "4.8.3"
  }
}

Finally, my tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/common/components/*"],
      "@styles/*": ["src/common/styles/*"],
      "@modules/*": ["src/modules/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

Would appreciate any help.

Thank you.

CodePudding user response:

Next.js seems to behave strangely sometimes. I fortunately managed to figure it out.

For some reason, exporting a function doesn't work, but exporting a constant anonymous function does.

I changed the file like so, and it's started working for some reason.

import type { AppProps } from "next/app";
import { Fragment } from "react";
import '@styles/globals.scss';

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <Fragment>
      <div>Hello world</div>
      <Component {...pageProps} />
    </Fragment>
  );
};

export default MyApp;

Wish I knew exactly why, but I'll take it.

  • Related