스토리북 파일 안에서 Typescript에서 설정한 절대 경로로 Import를 할 때 경로를 찾지 못하는 오류가 발생한다.

 

그럴 때는 tsconfig-paths-webpack-plugin을 설치하고 사용하면 된다.

 

.storybook/main.ts에서 tsconfig-paths-webpack-plugin를 불러와주고

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

 

config 객체 안에 코드를 넣어준다.

const config: StorybookConfig = {
	... 생략 ...
    
	webpackFinal: async (config: Configuration) => {
        if (!config.resolve) {
            config.resolve = {};
        }

        if (!config.resolve.plugins) {
            config.resolve.plugins = [];
        }

        config.resolve.plugins.push(new TsconfigPathsPlugin({}));

        return config;
    }
}
 
 

 

 

반응형

Next.js는 node_modules의 일부 파일을 포함하여 프로덕션 배포에 필요한 파일만 복사하는 독립 실행형 폴더를 자동으로 생성할 수 있다.

 

이 기능을 사용하기 위해서는 next.config.js에서 아래와 같이 활성화를 해주면 된다.

module.exports = {
  output: 'standalone',
}

이렇게 하면 .next/standalone에 폴더가 생성되며, 이 폴더는 node_modules를 설치하지 않고도 자체적으로 배포할 수 있다.

 

또한 next start 대신 사용할 수 있는 server.js 파일도 생성된다. 이 서버는 기본적으로 public 또는 .next/static 폴더를 복사하지 않는다. 이러한 폴더는 CDN에서 처리하는 것이 이상적이지만, 이러한 폴더를 standalone/publicstandalone/.next/static 정적 폴더에 수동으로 복사할 수 있으며, 그 후에는 server.js 파일이 자동으로 해당 폴더를 서비스한다.

 

운영 서버에 npm run build를 통해 생성된 .next/standalone 폴더만 업로드 하면 되고 node server.js로 실행하면 된다. 

 

추가적으로 .next/static을 CDN으로 처리를 하려 한다. 

next.config.js에서 assetPrefix 옵션에 CDN의 URL을 추가해주면 CDN 안에서 .next/static 를 찾게 된다.

 

module.exports = {
    output: 'standalone',
    reactStrictMode: false,
    swcMinify: true,
    assetPrefix: 'https://cdn.mydomain.com'
};

아래 보면 cdn 폴더 경로를 보면 .next가 아닌 _next로 찾게 되기 때문에 폴더명을 변경해줘야한다.

 

반응형

Next.js에서 단위 테스트를 하기 위해서 공식 문서에서 설명하는 Jest와 React Testing Library를 사용했다.

 

먼저 4개의 라이브러리를 설치한다. jest, jest-environment-jsdom, @testing-library/react, @testing-library/jest-dom

npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

 

루트 경로에 jest.config.mjs 파일을 생성하여 아래와 같이 내용을 추가해준다.

import nextJest from 'next/jest'
 
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})
 
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
 
  testEnvironment: 'jest-environment-jsdom',
}
 
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

Next.js에서 SWC 컴파일러를 사용하기 때문에 더 이상 설정은 필요 없다.

 

버튼 컴포넌트의 테스트 코드를 작성해봤다.

import { render } from '@testing-library/react';

import Button from './index';

it('button component snapshot', () => {
    const buttonRender = render(
        <Button type="button" onClick={() => console.log('button onClick')}>
            Test Button
        </Button>
    );

    expect(buttonRender.container).toMatchSnapshot();
});

테스트 코드도 잘 통과 됐고 아래와 같이 스냅샷도 생성이 됐다.

 

마지막으로 package.json에서 test 스크립트를 추가 했다.

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "jest --watch"
  }
}

 

웹스톰에서는 동작에는 문제 없지만 코드에 문제 있다는 경고를 표시했다. @types/jest를 설치해주니 말끔하게 해결했다.

npm i --save-dev @types/jest

 

반응형

+ Recent posts