npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

testjun001

v0.0.5

Published

npm modules

Downloads

20

Readme

NPM에 버튼 컴포넌트 배포하기

Step 1: 프로젝트 설정

프로젝트를 시작하기 전에, 우선 upstream 저장소에서 최신 변경 사항을 가져옵니다.

upstream의 코드를 pull한 후 터미널에서 다음 명령어를 실행합니다.

git pull upstream main
cd button-component
npm install

git pull upstream main: 이 명령어는 upstream 저장소의 main 브랜치에서 최신 변경 사항을 가져와 현재 로컬 저장소와 병합합니다. 이를 통해 프로젝트의 최신 코드를 받아올 수 있습니다.

Step 2: 버튼 컴포넌트 작성

이제 재사용 가능한 버튼 컴포넌트를 작성해보겠습니다. 프로젝트 내 src/lib/components 폴더에 Button.tsx 파일을 생성하고 컴포넌트 코드를 작성합니다.

import React from "react";

interface ButtonProps {
  label: string;
  onClick: () => void;
}

const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
  return <button onClick={onClick}>{label}</button>;
};

export default Button;

label은 버튼에 표시될 텍스트이며, onClick은 버튼 클릭 시 호출될 함수입니다. 그리고 Button 컴포넌트를 함수형 컴포넌트로 정의하고, React.FC 타입으로 지정합니다.

Step 3: 컴포넌트 테스트

작성한 버튼 컴포넌트가 제대로 동작하는지 테스트 해봅니다. App.tsx 파일에서 버튼 컴포넌트를 import하고 사용합니다.

import React from "react";
import Button from "./lib/components/Button";

const App: React.FC = () => {
  const handleClick = () => {
    alert("Button clicked!");
  };

  return (
    <div>
      <h1>Button Component Example</h1>
      <Button label="Click me" onClick={handleClick} />
    </div>
  );
};

export default App;

여기서는 handleClick 함수를 정의하여 버튼 클릭 시 동작을 지정하고, Button 컴포넌트에 labelonClick 속성을 전달하여 사용합니다.

개발 서버 실행

터미널에서 npm run dev 명령어를 실행하여 개발 서버를 실행합니다. 브라우저에서 버튼이 잘 동작하는지 확인합니다.

Step 4: Vite 설정 수정과 컴포넌트 Export

버튼 컴포넌트를 npm에 배포하기 위해서는 몇 가지 설정이 필요합니다. Vite의 설정을 수정하여 컴포넌트를 라이브러리로 빌드하고 타입 선언 파일을 생성할 수 있습니다.

패키지 설치

먼저 필요한 패키지를 설치합니다. 터미널에서 다음 명령어를 입력합니다.

npm i -D path @types/node vite-plugin-dts
  • path: 파일 경로를 다루기 위한 Node.js 내장 모듈입니다.
  • @types/node: Node.js 타입 정의 파일입니다. Vite 설정에서 path 모듈을 사용하기 위해 필요합니다.
  • vite-plugin-dts: Vite 플러그인으로, 타입 선언 파일(.d.ts)을 생성해줍니다.

컴포넌트 Export

버튼 컴포넌트를 외부에서 사용할 수 있도록 export 합니다. src/lib/index.tsx 파일을 생성하고 버튼 컴포넌트를 export 합니다.

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

이렇게 하면 다른 곳에서 버튼 컴포넌트를 import 할 때 import { Button } from "./lib";와 같은 방식으로 사용할 수 있습니다.

vite.config.ts 수정

vite.config.ts 파일을 다음과 같이 수정합니다.

import * as path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";

export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, "src/lib/index.tsx"),
      name: "index",
      fileName: "index",
    },
    rollupOptions: {
      external: ["react"],
      output: {
        globals: {
          react: "React",
        },
      },
    },
    commonjsOptions: {
      esmExternals: ["react"],
    },
  },
  plugins: [react()],
});

build.lib: 이 설정은 라이브러리로 빌드할 때 사용되는 옵션들을 지정합니다.

  • entry
    • 라이브러리의 엔트리 포인트를 설정합니다. 여기서는 src/lib/index.tsx 파일을 엔트리 포인트로 지정하였습니다. 이 파일을 기준으로 라이브러리에 포함될 모든 코드가 번들링됩니다. 여기서는 src/lib/index.tsx 파일을 엔트리 포인트로 설정하였습니다. 이는 index.tsx 파일이 라이브러리의 메인 파일 역할을 한다는 것을 의미합니다.
  • name
    • 라이브러리가 전역 변수로 노출될 때 사용될 이름을 설정합니다. 예를 들어, name을 "MyLibrary"로 설정하면 다른 프로젝트에서 <script> 태그를 통해 라이브러리를 사용할 때 window.MyLibrary와 같은 방식으로 접근할 수 있습니다. 하지만 리액트 프로젝트에서는 주로 모듈 시스템을 사용하므로 전역 변수로 노출되는 경우는 드뭅니다. 이 이름은 UMD 포맷으로 빌드할 때 사용됩니다.
  • fileName
    • 빌드 결과로 생성되는 파일의 이름을 설정합니다. 예를 들어, fileName을 "index"로 설정하면 빌드 후에 dist 폴더에 index.js와 같은 파일이 생성됩니다.
  • plugins: 사용할 Vite 플러그인을 설정합니다. react 플러그인과 dts 플러그인을 사용하도록 설정하였습니다.

tsconfig.json 수정

tsconfig.json 파일의 include 속성에 src/lib를 추가하여 라이브러리 폴더의 파일들이 컴파일되도록 합니다.

{
  "include": ["src/lib"]
}

빌드 실행

설정이 완료되었으면 터미널에서 다음 명령어를 입력하여 컴포넌트를 빌드합니다.

npm run build

빌드가 성공적으로 완료되면 dist 폴더에 컴포넌트의 번들링된 파일과 타입 선언 파일이 생성됩니다.

Step 5: npm에 배포

이제 버튼 컴포넌트를 npm에 배포할 준비가 되었습니다. npm에 배포하려면 package.json 파일을 수정하고, 필요한 설정을 추가해야 합니다.

package.json 파일 수정

npm에 배포하기 위해 package.json 파일을 다음과 같이 수정합니다.

{
  "name": "{고유한 네이밍}",
  "version": "0.0.0",
  "description": "A simple button component",
  "type": "module",
  "main": "dist/index.umd.cjs",
  "module": "dist/index.js",
  "files": ["dist"]
}
  • name: 패키지의 이름을 지정합니다. npm에 배포할 때는 고유한 이름을 사용해야 합니다. 일반적으로 @사용자명/패키지명 형식을 사용합니다.
  • version: 패키지의 버전을 지정합니다. 시맨틱 버전닝(Semantic Versioning) 규칙을 따르는 것이 좋습니다.
  • description: 패키지에 대한 간단한 설명을 작성합니다.
  • main: CommonJS 모듈 시스템에서 사용할 진입점 파일을 지정합니다.
  • module: ECMAScript 모듈 시스템에서 사용할 진입점 파일을 지정합니다.
  • files: npm 패키지에 포함할 파일들을 명시합니다. 여기서는 dist 폴더의 내용만 포함하도록 설정하였습니다.

npm 로그인 및 배포

터미널에서 다음 명령어를 실행하여 npm에 로그인하고 패키지를 배포합니다.

npm login
npm publish

버전 업데이트 및 재배포

만약 한번이라도 배포를 했다면, npm에는 동일한 버전을 다시 배포할 수 없습니다. 그럴 때는 이미 배포한 패키지의 버전을 업데이트하고 다시 배포하려면 다음 명령어를 사용합니다.

npm version patch
npm publish
  • npm version patch: 패키지의 패치 버전을 증가시킵니다. minormajor 옵션을 사용하여 마이너 버전이나 메이저 버전을 증가시킬 수도 있습니다.
    • 시맨틱 버전닝은 버전 번호를 메이저.마이너.패치 형식으로 표기하는 것입니다. 주로 메이저 버전은 기존 버전과 호환되지 않는 변경사항이 있을 때, 마이너 버전은 기능 추가나 개선이 있을 때, 패치 버전은 버그 수정이 있을 때 증가시킵니다.
  • npm publish: 업데이트된 버전의 패키지를 다시 배포합니다.

Step 6: 컴포넌트 사용

이제 npm에 배포한 버튼 컴포넌트를 실제로 사용해보겠습니다. 다른 개발자들도 우리가 만든 컴포넌트를 npm을 통해 설치하고 사용할 수 있습니다.

컴포넌트 설치

먼저 npm에 배포한 버튼 컴포넌트를 설치합니다. 터미널에서 다음 명령어를 실행합니다.

npm install {배포한 패키지 이름}

컴포넌트 사용

설치한 버튼 컴포넌트를 프로젝트에서 사용하려면 다음과 같이 컴포넌트를 import하고 사용합니다.

import React from "react";
import { Button } from "button-component-xxx";

const App: React.FC = () => {
  const handleClick = () => {
    alert("Button clicked!");
  };

  return (
    <div>
      <h1>Using Button Component from npm</h1>
      <Button label="Click me" onClick={handleClick} />
    </div>
  );
};

export default App;

위와 같이 컴포넌트를 import하고 사용함으로써 npm에 배포한 버튼 컴포넌트를 프로젝트에 통합할 수 있습니다.