Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발하는 녹차

Vite + React + Typescript를 이용해서 NPM 배포하기 - 1 본문

React

Vite + React + Typescript를 이용해서 NPM 배포하기 - 1

gosung_greentea 2024. 6. 15. 00:25

보통 React 프로젝트를 생성할 때 CRA(Create-React-App) 방식을 주로 사용하여 작업했지만, 이를 사용하면 번들러로 Webpack을 사용하게 되는데 프로젝트의 크기가 커질 수록 속도가 상당히 느려지는 것을 알 수 있다. 이를 해결하기 위해 Vite를 사용하여 React 프로젝트를 생성하는 것을 선택했다. esbuild를 번들러로 사용하기 때문에 보다 빠르고 간결하게 이용이 가능하다.

 

💻 프로젝트 생성하기

npm create vite@latest [프로젝트 명] --template react-ts
cd [프로젝트 명] && npm install

불필요한 파일 삭제하기

아래의 불필요한 파일들을 모두 삭제한다.

  • public
  • assets
  • App.css
  • App.tsx
  • main.tsx
  • index.html

💨 tailwindcss 설치

npm i -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

 

위의 명령어를 실행하면 postcss.config.js와 tailwind.config.js 파일이 생성된다. 그 후, tailwind.config.js 파일 내 content에 src를 명시해준다.

// tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
    content: ["./src/**/*.{js,jsx,ts,tsx}"],
    theme: {
        extend: {},
    },
    plugins: [],
};

 

그리고 src/index.css에 tailwind 관련 코드를 import 해준다.

@tailwind base;
@tailwind components;
@tailwind utilities;

🎲 컴포넌트 작성

src 폴더 아래 components 폴더를 생성하고, Button 컴포넌트를 작성한다.

// src/components/Button.tsx

type ButtonProps = { children: React.ReactNode };

const Button = ({ children }: ButtonProps) => {
	return (
    	<button className="border py-2 px-4 text-sm rounded-full">
        	{children}
        </button>
    );
};

export default Button;

 

src/index.ts 파일에 예시로 만들었던 Button 컴포넌트를 export 해주고, tailwind가 작성되어 있는 index.css를 import 해준다.

// src/index.ts

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

 

지금까지의 폴더 구조는 아래와 같다.

폴더 구조

📦 package.json 수정

{
  "name": "이름",
  "private": false,
  "version": "0.0.0",
  "type": "module",
  "main": "./dist/index.umd.js",
  "module": "./dist/index.es.js",
  "types": "./dist/index.d.ts",
  "files": [
    "dist"
  ],
  "exports": {
    ".": {
      "import": "./dist/index.es.js",
      "require": "./dist/index.umd.js",
      "types": "./dist/index.d.ts"
    },
    "./dist/style.css": "./dist/style.css"
  },
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@typescript-eslint/eslint-plugin": "^7.2.0",
    "@typescript-eslint/parser": "^7.2.0",
    "@vitejs/plugin-react": "^4.2.1",
    "autoprefixer": "^10.4.19",
    "eslint": "^8.57.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "postcss": "^8.4.38",
    "tailwindcss": "^3.4.4",
    "typescript": "^5.2.2",
    "vite": "^5.2.0"
  }
}
  • name
    npm에 등록할 패키지 이름으로, npm에 패키지를 등록할 때 중복되지 않아야 하므로 npm에 검색한 후 이름을 선정해야 한다.
  • private
    해당 패키지를 다른 사용자들에게 공개할 지 비공개할 지에 대해 설정한다. 비공개로 설정할 경우 유료이므로, 값을 false로 해준다.
  • main
    라이브러리의 진입점인 엔트리 파일을 지정해준다.
  • types
    타입들이 선언되어 있는 엔트리 파일을 지정해준다.

✅ tsconfig.json 수정

 

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "declaration": true,
    "typeRoots": ["./dist/index.d.ts"],
    
    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

😆 vite.config.js 수정

타입스크립트를 사용하고 있기 때문에 vite-plugin-dts와 @types/node 패키지를 설치해줘야 한다.

npm i -D vite-plugin-dts @types/node

 

설치를 마치고, vite.config.js를 아래와 같이 수정한다.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
import dts from "vite-plugin-dts";
import tailwindcss from "tailwindcss";

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, "./src/index.ts"),
      name: "이름",
      fileName: (format) => `index.${format}.js`,
    },
    rollupOptions: {
      external: ["react", "react-dom", "tailwindcss"],
      output: {
        globals: {
          react: "React",
          "react-dom": "ReactDOM",
          tailwindcss: "tailwindcss",
        },
      },
    },
    sourcemap: true,
    emptyOutDir: true,
  },
  plugins: [react(), dts({ rollupTypes: true })],
  css: {
    postcss: {
      plugins: [tailwindcss],
    },
  },
});

 

예시로 작성한 Button 컴포넌트를 npm run build를 통해 실행하면 dist 폴더가 생성된다.

 

📛 npm 배포

npm 회원가입이 안 되어 있다면, 회원가입을 진행한 후 아래 명령어를 입력해야 한다.

npm login
npm run build
npm publish

 

이제 실제 사용 가능한 라이브러리를 한 번 만들어보도록 하겠습니다.

🔗 참고 링크

https://jgjgill-blog.netlify.app/post/create-your-own-component-library/ 

https://medium.com/@devparkoon/vite%EC%99%80-tailwindcss%EB%A1%9C-react-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-storybook-%EC%84%A4%EC%A0%95%EB%B6%80%ED%84%B0-npm-%EB%B0%B0%ED%8F%AC%EA%B9%8C%EC%A7%80-e3bf2821cf50

'React' 카테고리의 다른 글

Vite + React + Typescript를 이용해서 NPM 배포하기 - 2  (0) 2024.06.18