Martyn Ball
Martyn Ball

Reputation: 4885

NextJS image alias not working on page within sub-directories

i'm trying to setup an alias to my images so that I can link to them regardless as to where my component is.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@lib/*": ["lib/*"],
      "@images/*": ["images/*"]
    }

As you can see I have setup an alias, tried multiple ways even including the public path, however none of them seem to work...

For example on {project}/pages/index.tsx I have to link the image as follows in order for it to load:

import Header from '@lib/components/Header';

<Header className="h-128" image="./images/hero.jpg">
...
// Header.tsx

import Image from 'next/image';
import { ReactElement } from 'react';

export interface HeaderProps {
    children?: ReactElement | ReactElement[];
    className?: string;
    image?: string;
}

const Header = ({ children, className, image }: HeaderProps) => {
    return (
        <section
            className={`m-0 flex relative after:shadow-vignette after:content-[''] after:w-full after:h-full after:absolute ${className}`}
        >
            <div className="absolute h-full w-full z-0">
                <Image unoptimized className="z-0" layout="fill" objectFit="cover" src={image} />
            </div>
            <div className="container text-center m-auto z-10">{children}</div>
        </section>
    );
};

export default Header;

This becomes even more of an issue when I attempt to link to an image within {project}/pages/sub-directory/page-two.tsx

Upvotes: 0

Views: 1627

Answers (1)

FINDarkside
FINDarkside

Reputation: 2435

compilerOptions.paths is a TypeScript setting, it doesn't affect how Next.js or the browser loads images. Put those images inside public/images/ and you can load them like you're doing right now.

Alternatively import the image instead of just using a string to identify it.

import img from '@images/hero.jpg';

const Asd = () => (
  <Image src={img} />
)

Should work.

Upvotes: 0

Related Questions