상현에 하루하루
개발자의 하루

Next.js tsconfig 절대경로 설정시 Module not found: Can’t resolve ‘fs’

( 업데이트: )

Next.js --typescript를 세팅하고 절대경로를 적용을 하였다.

Advanced Features: Absolute Imports and Module Path Aliases | Next.js

// tsconfig.json or jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "."
  }
}Code language: JSON / JSON with Comments (json)

절대경로를 설정하고 src/pages/products/[slug].tsxgetStaticPropsgetStaticPaths가 있는 파일에서 절대경로를 통해서 컴포넌트를 가져와서 사용했다.

fs 등등 여러개의 모듈을 찾을 수 없다는 에러메세지가 나온다. 무엇 때문일까?

Next.js의 문제가아니었다. 오류에도 나와있는데 twin.macro 라이브러리 때문에 발생하는 문제였다.

  • https://twitter.com/HamatoYogi/status/1428225954531393537
  • https://github.com/ben-rogerson/twin.macro/discussions/516

현재 Next.js 12버전부터는 컴파일러를 SWC를 사용하고있습니다. twin.macro는 babel-plugin-macro를 사용하기 때문에 위와 같은 오류가 생깁니다.

SWC 컴파일을 사용하면서 twin.macro를 써야할까? 아니면 twin.macro를 버리고 SWC를 사용할까 그게 고민이다

Next.js 12의 기본 컴파일러로 SWC가 사용되어서 SWC를 사용하기로 결정했다. twin.macro를 잘 사용하였지만 SWC 컴파일러 버전이 나올때까지는 defaultProps에 클래스이름으로 넣기로 결정했다.

defaultProps를 넣으면서 생기는 TypeScript문제

// We extend from React.HTMLAttributes to get all the HTML attributes
// Don't extend React.HTMLProps!
export interface IGreenBoxProps extends React.HTMLAttributes<HTMLDivElement> {
    title: string;
}

class GreenBox extends React.Component<IGreenBoxProps, void> {
    public render() {
        // If you don't spread children and title, the restProps
        // still contain these props and compiler will say "no"
        const {children, title, ...divAttributes} = this.props;

        return (
            <div {...divAttributes} style={{backgroundColor: "green"}}>
                <h1>{title}</h1>
                {children}
            </div>
        );
    }
}

const myGreenBox = <GreenBox title="Hello" onClick={() => alert("Hello")}/>;Code language: JavaScript (javascript)

React.FC을 사용하고있지만 React.FC은 children까지만 정의되어있다.

const Button = styled.button``;
Button.defaultProps = {
  className: `px-[16px]`
}
const BlackButton: React.FC<React.HTMLAttributes<HTMLButtonElement> | undefined> = ({ children,...props }) => {
  return <button {...props} className={`${Button.defaultProps?.className} ${props.className}`} >button test</button>
});Code language: JavaScript (javascript)