TS 및 롤업으로 재사용 가능한 React 구성 요소 만들기

오늘날 프론트엔드 개발자라면 react가 resisability의 동의어라는 것을 알고 있을 것입니다. 구성 요소 기반 아키텍처를 생성하도록 설계된 라이브러리입니다.

당신이 한 번에 여러 사이드 프로젝트를 시작하는 나쁜 습관이 있는 저와 같은 개발자라면 인생에서 적어도 한 번은 모든 반응 구성 요소의 컬렉션을 만들어 모든 프로젝트에서 재사용하는 것을 생각했을 것입니다.

그렇지 않다면 걱정하지 마세요. 오늘이 기회를 주기에 가장 좋은 때입니다. 이 생각은 2020년에 제 마음에 떠오른 이후 저는 제 미래의 모든 사이드 프로젝트를 위한 원스톱 솔루션을 만들기 위해 노력하고 있습니다.

이 게시물에서는 npm에 게시하고 다른 패키지로 사용할 수 있는 재사용 가능한 구성 요소 패키지를 만들기 위해 프로젝트를 설정하는 방법을 공유합니다.

기술 스택


  • 타입스크립트
  • 리액트
  • 롤업

  • 먼저 프로젝트를 설정합니다.
    쉽게 따라할 수 있도록 정확히 동일한 폴더 구조를 따르라고 말하고 싶습니다.

    📦react-lib
     ┣ 📂build
     ┣ 📂src
     ┃ ┣ 📂components
     ┃ ┃ ┗ 📜Button.tsx
     ┃ ┗ 📜index.tsx
     ┣ 📜package.json
     ┣ 📜rollup.config.js
     ┣ 📜tsconfig.json
     ┗ 📜yarn.lock
    


    우선 package.json에 추가해야 하는 몇 가지 필수 항목이 있습니다.

    패키지.json

    {
      "name": "react-lib",
      "version": "1.0.0",
      // Main will tell node to enter our library from this file (basically it will act as a entry point)
      "main": "build/index.js",
      "scripts": {
        "build": "rollup -c"
      },
      //These are dependencies we need only in the development process
      "devDependencies": {
        "@rollup/plugin-commonjs": "^21.0.2",
        "@types/react": "^17.0.41",
        "@types/react-dom": "^17.0.14",
        "rollup": "^2.70.1",
        "rollup-plugin-typescript2": "^0.31.2",
        "typescript": "^4.6.2"
      },
      //The files will define where our final bundle is located
      "files": [
        "build"
      ],
      "dependencies": {},
      //React and React DOM will peer dependencies because they will already be present in the project this package is being used.
      "peerDependencies": {
        "react": "^17.0.2",
        "react-dom": "^17.0.2"
      }
    }
    


    처음에는 webpack을 사용해서 코드를 묶었는데 이해하고 유지하기가 쉽지 않았고, 나중에는 gulp로 바꿨는데 gulp가 충분히 강력하지 않았고 세 번째로 롤업을 하게 된 것이 매력이라고 하던데 webpack처럼 강력하고 꿀꺽 꿀꺽처럼 구성하기 쉬웠습니다

    롤업 파일은 이 프로젝트에서 가장 중요한 파일이며 라이브러리를 빌드합니다.

    rollup.config.js

    import typescript from "rollup-plugin-typescript2";
    
    export default {
      //Will act as a entry point
      input: "./src/index.tsx",
      output: [
        {
          //Specify the output directory
          dir: "build",
          //We will be using commonjs as a format for bundling
          format: "cjs",
          exports: "named",
          //It will provide you the sourcemap for debugging
          sourcemap: true,
          strict: false,
        },
      ],
      //Preserve module will generate a transpiled file for every file in your src folder, if set false it will bundle all the code in one file
      preserveModules: true,
      //Rollup allows a rich set of plugins to be used along side, we are only using one to compile typescript code to JS
      plugins: [typescript({ tsconfig: "./tsconfig.json" })],
      //We will add React and React-dom as externals because our library will use these two packages from its parent
      external: ["react", "react-dom"],
    };
    


    다음 파일은 tsconfig.json입니다. 정말 간단하게 유지했지만 필요와 표준에 따라 변경할 수 있습니다.

    tsconfig.json

    {
      "compilerOptions": {
        "module": "esnext",
        "declaration": true,
        "rootDir": "src",
        "outDir": "build",
        "target": "ES5",
        "moduleResolution": "Node",
        "jsx": "react",
        "noImplicitUseStrict": true,
        "allowSyntheticDefaultImports": true,
        "lib": ["es2015", "dom"]
      },
      "include": ["./src/*.tsx"],
      "exclude": ["node_modules", "build"]
    }
    


    이제 몇 가지 구성 요소를 작성해 보겠습니다. 이 게시물의 목적을 위해 저는 두 개의 소품 색상과 roundCorners를 허용하는 간단한 버튼 구성 요소를 만들었습니다.

    src/components/button.tsx 파일을 생성하고 아래 코드를 추가합니다.

    src/components/button.tsx

    import React from "react";
    
    interface Props {
      color?: string;
      roundCorners?: boolean;
    }
    
    const Button: React.FC<Props> = (props) => {
      const { color, roundCorners } = props;
    
      return (
        <button
          style={{ background: color, borderRadius: roundCorners ? "6px" : "0" }}
        >
          Click me
        </button>
      );
    };
    
    Button.defaultProps = {
      color: "white",
      roundCorners: false,
    };
    
    export default Button;
    


    이제 src/index.tsx로 가져오면 빌드를 생성하고 프로젝트에서 사용할 준비가 됩니다.

    src/index.tsx

    export { default as Button } from "./components/Button";
    


    이제 선택한 터미널을 시작하고 다음 명령을 실행하여 빌드를 생성하십시오.

    yarn install
    yarn build
    


    모든 것이 제대로 완료되면 이 메시지가 표시될 수 있습니다.



    이제 로컬 프로젝트에서 사용하기 위해 yarn link 명령을 사용할 수 있습니다.

    먼저 라이브러리 프로젝트의 루트에서 아래 명령을 실행하면 장치에 심볼릭 링크가 생성됩니다.

    yarn link
    


    이제 모든 프로젝트에서 사용하려면 앱 디렉토리의 루트에서 아래 명령을 사용할 수 있습니다.

    yarn link react-lib
    


    아래 코드와 같이 사용할 수 있습니다.

    import { Button } from "react-lib";
    function App() {
      return <Button roundCorners={true} />;
    }
    
    export default App;
    


    최종 결과는 다음과 같습니다.



    버튼 이상의 무언가를 만드는 데 관심이 있다면 이 게시물을 작성할 아이디어를 제공한 프로젝트MoleculeUI를 살펴보십시오.

    앞으로 더 많은 콘텐츠를 보려면 팔로우하세요.
    첫 게시물인 만큼 피드백을 남겨주세요.
    감사합니다 😊

    좋은 웹페이지 즐겨찾기