• HOME
  • PRODUCT
  • DEVELOP
  • NEWS
  • CONSULTING
No Result
View All Result
illunex Blog
  • HOME
  • PRODUCT
  • DEVELOP
  • NEWS
  • CONSULTING
No Result
View All Result
일루넥스 블로그
No Result
View All Result

Create React Module(with Typescript)

Create React Module(with Typescript)

박 윤민 by 박 윤민
2021년 1월 7일
in DEVELOP, 프론트앤드
Create React Module(with Typescript)

안녕하세요, 일루넥스 개발팀 박윤민입니다.

컴포넌트 개발을 하다보면 만들어둔 컴포넌트를 재사용해야할 일이 생기기 마련입니다. 그럴때 미리 모듈로 설계를 해두면 다른곳에서 가져다 쓰기가 쉽습니다. 이번에는 그럴때를 대비해서 리액트 컴포넌트를 모듈로 만들어 보는 방법을 소개하고자 합니다.

1. 환경설정

먼저 다음 명령어를 통해 리액트 앱을 생성합니다.

npx create-react-app react-components-example 

그리고 이어서 타입스크립트 설치를 합니다.

npm i typescript
npm i -D @types/react 

설치하시게 되면 기본적으로 tsconfig.json 파일이 생성됩니다. resolveJsonModule을 삭제 하고 outDir을 넣어줍니다.

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "declaration": true,
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "outDir": "dist"
  },
  "include": [
    "src"
  ]
} 

App.js 파일을 App.tsx로 바꾸고 잘 작동하는지 확인해 봅니다.

2. 버튼 컴포넌트 생성

만들어 볼 모듈은 간단한 버튼 모듈로 props값에 따라 다른 버튼을 만들어 보겠습니다.

먼저 Button.tsx를 만들어 줍니다.

import React from "react";

const Button = () => {
    return (
        <button></button>
    )
} 

props에 따라 여러가지 버튼을 만들기위해서 props 타입을 정의 해줍니다.

import React from "react";

interface ButtonProps {
    style: any
    title: string
    onClick: any
}

const Button = (props:ButtonProps) => {
    return (
        <button></button>
    )
} 

props타입을 정의했으면 이제 props에 따라 버튼을 만들기만 하면 됩니다.

이 예제에서는 간단하게 스타일, 제목, 클릭이벤트만을 정의했습니다. 추가로 더 넣고 싶은것이 있다면 더 넣어서 만드시면 됩니다.

const Button = (props:ButtonProps) => {
    return (
        <button 
            style={props.style}
            onClick={props.onClick}
        >
            {props.title}
        </button>
    )
} 

최종적으로 완성된 버튼의 모습입니다.

그러면 버튼이 잘 작동하는지 테스트를 해보도록 하겠습니다.

3. Test

먼저 test도구를 설치 합니다.

npm i -D jest ts-jest @types/react-test-renderer react-test-renderer 

그리고 Button.test.tsx를 생성합니다. Button.test.tsx에서 Button 모듈을 사용하기 위해서 먼저 Button.tsx에서 모듈을 export 합니다.

export default Button 

이제 Button.test.tsx를 작성합니다.

import React from "react";
import renderer from "react-test-renderer";
import Button from "./Button";

test("component testing'", () => {
    const buttonProps = {
        style: {background: 'red'},
        title: '버튼',
        onClick: () => console.log('테스트!!')
    }
    const component = renderer.create(<Button {...buttonProps} />);
    const testInstance = component.root;
    expect(testInstance.findByType(Button).props.style).toBe(buttonProps.style);
    expect(testInstance.findByType(Button).props.title).toBe(buttonProps.title);
    expect(testInstance.findByType(Button).props.onClick).toBe(buttonProps.onClick);
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
}); 

테스트는 간단하게 buttonProps를 넘겨주고 Button컴포넌트가 잘 받았는지 확인합니다.

ts-jest를 사용하기 위해서 다음과같은 jest config파일을 만들어줍니다.

module.exports = {
    moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "json"],
    transform: {
        '^.+\\.(js|tsx)?$': 'ts-jest'
    },
    testEnvironment: 'node',
    moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/$1'
    },
    testMatch: [
        '<rootDir>/**/*.test.(js|jsx|ts|tsx)', '<rootDir>/(tests/unit/**/*.test.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
    ],
    transformIgnorePatterns: ['<rootDir>/node_modules/']
}; 

바로 jest명령어를 통해 테스트를 진행하면 App.test.js에서 에러가 발생합니다. 이 예제에서는 App.test.js는 중요하지 않기때문에 App.test.js를 삭제하고 테스를 진행합니다.

테스트를 진행하면 다음과 같은 화면을 보시게 됩니다.

4. 버튼 컴포넌트 렌더링 확인

그럼 이제 Button모듈을 불러와서 화면에 잘 나오는지 확인해보도록 하겠습니다.

App.tsx파일을 다음과 같이 수정합니다.

import './App.css';
import Button from "./Button";

function App() {
  return (
    <div className="App">
      <Button
          style={{background:'red'}}
          title={'버튼'}
          onClick={()=>console.log('테스트!!')}
      />
    </div>
  );
}

export default App; 

그리고 실행을 하시게 되면 에러가 발생합니다.

jest를 버전 지정하지 않고 설치하시게되면 현재 26.6.3버전이 설치되며 26.6.0버전까지 호환된다고 나옵니다. 그러므로 26.6.0 버전으로 다운그레이드를 진행하면 됩니다.

※ 2021-01-03기준이며 호환되는 버전은 달라질 수 있습니다.

실행하시게 되면 빨간색 작은 버튼하나가 나타납니다.

클릭하시게되면 정상적으로 콘솔창에 테스트!!라고 나올 것입니다.

5. 모듈 업로드

이제 준비는 다 끝났습니다. 이제 모듈을 업로드하고 받아서 잘 실행되는지 확인하면 됩니다.

먼저 .npmignore파일을 생성합니다. Button모듈만 필요하므로 다음과 같이 작성합니다.

*
!dist/Button.d.ts
!dist/Button.js 

package.json파일도 수정합니다.

private을 삭제하고 npm모듈을 올릴 주소를 지정합니다.

"publishConfig": {
    "registry": "registry Address"
  }, 

npmjs에 업로드 하기 위해서는 회원가입을 해야하기에 이 예제에서는 사설 저장소에 업로드 하도록 하겠습니다.

tsc 명령어로 빌드하시게 되면 dist폴더가 생성됩니다. 마지막으로 다음 명령어를 실행하시면

npm publish 

다음과 같이 정상적으로 업로드 된 모습을 보실 수 있습니다.

6. 모듈 확인

이제 모듈을 다운받아 잘 작동하는지 확인해보겠습니다.

npm i react-components-example 

명령어를 실행하게 되면 프로젝트명이 일치하기 때문에 설치가 되지 않습니다.

그러므로 현재 프로젝트명칭을 react-components-example-test로 바꿔서 진행하겠습니다.

설치가 되었으면 다음과 같이 확인해봅니다.

import './App.css';
import Button from "react-components-example/dist/Button.js";


function App() {
  return (
    <div className="App">
      <Button
          style={{background:'red'}}
          title={'버튼'}
          onClick={()=>console.log('테스트!!')}
      />
    </div>
  );
}

export default App; 

마치며

앞으로는 컴포넌트들을 잘 만들어서 모듈로 만들어두고 바퀴의 재발명같은 안타까운 일이 좀 줄어들었으면 좋겠습니다. 관련 소스는 https://github.com/pymc20/react-components-example 에서 확인 하실 수 있습니다.

감사합니다.

Tags: componentmoduleReacttypescript
ShareTweet
Previous Post

CSS 방법론 - OOCSS

Next Post

MiniKube에서 배포해보기

Next Post
MiniKube에서 배포해보기

MiniKube에서 배포해보기

  • Copyright © 2020 illunex., Inc., All Rights Reserved.
  • 개인정보보호정책
No Result
View All Result
  • HOME
  • PRODUCT
  • DEVELOP
  • NEWS
  • CONSULTING