TypeScript 및 Emotion으로 React 구성 요소 게시 및 재사용

소개



일반적으로 타이핑을 제외하고 TypeScript 코드를 NPM 데이터베이스에 게시해서는 안 됩니다. 일반적인 접근 방식은 코드를 CommonJS(cjs) 및/또는 ES 모듈(esm)로 변환한 다음 게시하는 것입니다. 이를 수행하는 쉬운 방법은 RollupJS 입니다.

그럼에도 불구하고 Emotion을 사용하는 구성 요소를 재사용 가능한 모듈로 변환하는 것은 어렵습니다. 게다가 TypeScript 코드를 직접 사용할 수 있도록 하지 않는 이유는 무엇입니까? (나중에 React 애플리케이션에서 재사용하는 것을 목표로 함).

여기에서는 TypeScript와 Emotion으로 작성된 여러 프로젝트(예: React 17 )에서 사용하는 간단하지만 강력한 https://epop.net.br 구성 요소를 게시하는 접근 방식을 설명합니다.

코드는 GitHub에서 사용할 수 있습니다. https://github.com/cpmech/rcomps

내용물


  • Publishing TypeScript components
  • Reusing TypeScript Components
  • Emotion and React 17
  • Conclusion

  • TypeScript 구성 요소 게시

    NOTE: This procedure uses yarn , rsync , and jq .

    The idea is quite simple. First, copy all the .ts and .tsx files to the dist directory when calling yarn build . To do so, add this command to package.json :

    "build": "rm -rf dist && mkdir -p dist/rcomps && rsync -av src/components/* dist/rcomps --exclude __stories__ --exclude __tests__"
    

    Above, we remove any existent dist directory, create a subdirectory named dist/rcomps , which will help the consumer of this library to move it to the right place, and then copy the files using rsync (ignoring storybook and jest files).

    Second, for the yarn dist command, copy an alternative package-dist.json file to the dist directory by using this package.json command:

    "dist": "yarn build && cp package-dist.json dist/package.json && cd dist/ && yarn publish --access=public || true && cd .."
    

    Above, we call the build command, copy the two package-json files into dist, and then call yarn publish .

    The alternative (distributable) package-dist.json is:

    {
      "name": "<YOUR NPM PROJECT HERE>",
      "version": "0.1.0",
      "license": "MIT",
      "scripts": {
        "fix:ver1": "jq '.version = $newVal' --arg newVal `jq -r '.version' package.json` ../package.json > tmp.$$.json && mv -f tmp.$$.json ../package.json",
        "fix:ver2": "jq '.version = $newVal' --arg newVal `jq -r '.version' package.json` ../package-dist.json > tmp.$$.json && mv -f tmp.$$.json ../package-dist.json",
        "git:add": "git add ../package.json ../package-dist.json",
        "git:tag": "git tag v`jq -r '.version' package.json`",
        "git:all": "yarn git:add && git commit -m 'Publish' && yarn git:tag && git push && git push --tags",
        "postpublish": "yarn fix:ver1 && yarn fix:ver2 && yarn git:all"
      },
      "repository": "<YOUR GITHUB REPO HERE>",
      "description": "TypeScript React Components with Emotion"
    }
    

    The above code will automatically tag the git repository and fix the version numbers in both the main package.json and the publishable (alternative) package-dist.json. Each sub-command is explained below:

    • fix:ver1 fixes the version in the parent package.json file
    • fix:ver2 fixes the version in the distributable package-dist.json file
    • git:add takes the modifications in package.json and package-dist.json
    • git:tag creates a new tag based on the updated version in package.json
    • git:all runs "all" git commands, including adding, tagging, committing, pushing, and pushing tags
    • postpublish is the hook, called automatically by yarn publish , that will call the above sub-commands.

    TypeScript 구성 요소 재사용

    To reuse the TypeScript components, we have to copy the .ts and .tsx files from node_modules to the right place (e.g. the src directory of your create-react-app project). To do so, we add the following command to the scripts section of the app's package.json:

    "postinstall": "bash ./scripts/npm_postinstall.bash"
    

    The above command will be automatically called whenever we run yarn install .

    The auxiliary npm_postinstall.bash script is:

    #!/bin/bash
    set -e
    if [[ -d "./node_modules/@cpmech/rcomps/rcomps" ]]; then
        echo ">>> moving rcomps to src <<<"
        rm -rf ./src/rcomps
        mv ./node_modules/@cpmech/rcomps/rcomps ./src/
    fi
    

    The above script simply removes any existent ./src/rcomps directory from your React app and copy it again from the node_modules . NOTE: we have to move the rcomps directory from node_modules because react-scripts start or react-scripts test may complain if they find TypeScript files inside node_modules .

    Now, you can simply (for example):

    yarn add @cpmech/rcomps
    

    감성JS와 리액트 17

    Emotion 환상적이다! 실제 CSS를 작성하여 구성 요소의 스타일을 지정할 수 있습니다. 그래서 모든 것이 가능합니다! 예를 들어, 다음은 HTML 입력 요소see our inputElementCss.ts file에 대한 CSS입니다.

      const common = `
        position: relative;
        height: ${height}px;
        margin-top: ${marginTop}px;
        width: ${width};
        input {
          font-size: ${fontSize}px;
          box-sizing: border-box;
          height: ${height}px;
          width: 100%;
          padding-left: ${paddingHoriz}px;
          padding-right: ${pickerMode ? paddingRightPicker : paddingHoriz}px;
          border: ${borderWidth}px solid ${borderColor};
          border-radius: ${borderRadius}px;
          ${flatLeft ? `border-top-left-radius:0;border-bottom-left-radius:0;` : ''}
          ${flatRight ? `border-top-right-radius:0;border-bottom-right-radius:0;` : ''}
          color: ${textMode ? mutedColor : color};
          background-color: ${bgColor};
          resize: none;
          outline: none;
          ${pickerMode && !textMode ? `cursor:pointer;` : ''}
          ${
            pickerMode
              ? `text-overflow: ellipsis;
                 white-space: nowrap;
                 overflow: hidden;`
              : ''
          }
        }
        input[required] + label[placeholder] {
          display: block;
          pointer-events: none;
          line-height: ${labelFontSize}px;
          margin-top: -${deltaLabel}px;
        }
      `;
    


    위에서 표준 React로 할 수 없는 input[required] + label[placeholder] 사용에 유의하십시오.

    더 이상 React를 가져올 필요가 없는 React 17과 함께 EmotionJS를 사용하려면 TypeScript 코드 상단에 다음 줄을 추가하기만 하면 됩니다.

    /** @jsxImportSource @emotion/react */
    import { css } from '@emotion/react';
    


    그런 다음 다음과 같이 사용하십시오.

    export const RcProgress: React.FC<RcProgressProps> = ({
      progress,
      color = '#ffffff',
      backgroundColor = '#e5e5e5',
      borderColor,
      barColor = '#4d50c6',
      borderRadius = 300,
    }) => {
      const p = progress || 0;
      const width = p < 0 ? 0 : p > 100 ? 100 : p;
      return (
        <div
          css={css`
            ${backgroundColor ? `background-color: ${backgroundColor};` : ''}
            ${borderColor ? `border: 1px solid ${borderColor};` : ''}
            border-radius: ${borderRadius}px;
          `}
        >
          <div
            css={css`
              height: 24px;
              width: ${width}%;
              color: ${color};
              font-weight: bold;
              font-size: 15px;
              line-height: 1.5;
              background-color: ${barColor};
              border-radius: ${borderRadius}px;
              text-align: center;
              padding-top: 1px;
            `}
          >
            {width > 3 && `${width}%`}
          </div>
        </div>
      );
    };
    


    결론

    The development process with TypeScript and React 17 is quite enjoyable these days. The create-react-app makes the bootstrapping process much easier (e.g. yarn create react-app myapp --template typescript ). We also suggest using EmotionJS for styling the React components because we can do much more than with standard React. Finally, it is possible and convenient to make your TypeScript Components directly available on NPM.

    PS: check out our components :-)

    좋은 웹페이지 즐겨찾기