본문 바로가기
Node package

Vue github package 만들기

by devebucks 2022. 6. 29.
728x90

작업 순서

1. 깃허브 래포 생성

2. vue-cli로 vue 프로젝트 생성

3. package.json 수정

(깃헙 오너이름: the user or organization account that owns the repository containing your project.)

  • name키에는 @깃헙 오너이름/프로젝트 이름
  • private 키는 false로 수정
  • repository 키에 해당 프로젝트 깃헙 레포지토리 url 입력
  • publishConfig 키 추가
"publishConfig": {
  "registry":"https://npm.pkg.github.com"
},
  • npm build-lib 명령어 터미널에서 실행

완성본

{
  "name": "@깃헙원격지이름/vue-cropper",
  "author": {
    "name": "작성자 이름"
  },
  "repository": "git://github.com/깃헙원격지이름/vue-cropper.git",
  "version": "0.1.10",
  "private": false,
  "publishConfig": {
    "registry": "https://npm.pkg.github.com"
  },
  "main": "dist/vue-cropper.common.js",
"scripts": {
    "build-lib": "vue-cli-service build --target lib --name vue-cropper src/index.js",
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:mb": "yarn build:umd & yarn build:es & yarn build:unpkg",
    "build:umd": "rollup --config build/rollup.config.js --format umd --file dist/vue-cropper.umd.js",
    "build:es": "rollup --config build/rollup.config.js --format es --file dist/vue-cropper.esm.js",
    "build:unpkg": "rollup --config build/rollup.config.js --format iife --file dist/vue-cropper.min.js"
  },
  "peerDependencies": {
    "vue-advanced-cropper": "^1.11.1"
  },
  "dependencies": {},
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "rollup": "^2.75.7",
    "@rollup/plugin-alias": "^3.1.9",
    "@rollup/plugin-buble": "^0.21.3",
    "@rollup/plugin-commonjs": "^11.1.0",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "core-js": "^3.8.3",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-vue": "^5.0.1",
    "vue": "^2.6.14",
    "vue-advanced-cropper": "^1.11.1",
    "vue-template-compiler": "^2.6.14"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

 

4. 프로젝트 루트경로에 .npmrc 파일을 생성

// 는 주석 아님.

TOKEN은 깃허브 어카운트 access_token임.

@오너:registry=https://npm.pkg.github.com

 

5. rollup 패키지 설치 및 설정파일 작성

설치 패키지

yarn install -D @rollup/plugin-alias @rollup/plugin-buble @rollup/plugin-commonjs @rollup/plugin-image rollup-plugin-import-css rollup-plugin-node-resolve rollup-plugin-scss rollup-plugin-vue

~/build/rollup.config.js 파일 생성 및 설정

import commonjs from "@rollup/plugin-commonjs"; // Convert CommonJS modules to ES6
import vue from "rollup-plugin-vue"; // Handle .vue SFC files
import buble from "@rollup/plugin-buble"; // Transpile/polyfill with reasonable browser support
import resolve from "rollup-plugin-node-resolve"; // node_modules에서 써드파티 모듈을 사용할 수 있게해주는 플러그인
import image from "@rollup/plugin-image"; // 이미지 파일을 함께 롤업해줌.
import alias from "@rollup/plugin-alias";
import css from "rollup-plugin-import-css"; // javascript로 css를 임포트해줍니다.
export default {
  input: "src/index.js", // Path relative to package.json
  output: {
    name: "VueCropper",
    exports: "named",
  },
  external: ["vue"],
  plugins: [
    vue({
      css: true, // Dynamically inject css as a <style> tag
      compileTemplate: true, // Explicitly convert template to render function
    }),
    commonjs(),
    resolve(),
    image(),
    alias({ vue$: require.resolve("vue/dist/vue.esm.js") }),
    css(),
    buble(), // Transpile to ES5
  ],
};

 

6. 빌드 후 나온 dist 파일까지 원격 리포지토리에 업로드

 

7. npm 로그인. 프로젝트 홈 경로 터미널에서 다음 명령어 입력

$ npm login --scope=@깃헙 오너이름 --registry=https://npm.pkg.github.com

> Username: USERNAME
> Password: TOKEN
> Email: PUBLIC-EMAIL-ADDRESS

 

8. npm publish 명령어 입력

배포 완료.

 

 


오류 / 해결방법

오류1

Your request could not be authenticated by the GitHub Packages service. Please ensure your access token is valid and has the appropriate scopes configured.

 

오류1 - 해결 방법

참고 -> https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-npm-registry#authenticating-to-github-packages

.npmrc 에 다음을 추가

@깃헙원격지이름:registry=https://npm.pkg.github.com

 

깃허브 개인 접근 토큰 만들기

깃허브 페이지 > 상단 네비 헤더 > 프로필 이미지 클릭 > Settings

Personal access tokens 탭

토큰 생성 Select scopes에서 다음을 체크

 

오류2

error An unexpected error occurred: "https://npm.pkg.github.com/@OWNER%2fvue-cropper: Your request could not be authenticated by the GitHub Packages service. Please ensure your access token is valid and has the appropriate scopes configured."

오류2 - 해결방법

 


다른 프로젝트에서 만든 패키지 적용하기

1. ~/.npmrc을 생성하고 내용 추가

@깃헙원격지이름:registry=https://npm.pkg.github.com

이부분에서 다음 코드도 함께 추가해서 패키지 설치할 때, 인증을 하기도 한다. 하지만, 되도록 코드상에 토큰을 남기지 않는 것이 좋다.

//npm.pkg.github.com/:_authToken=TOKEN

 

깃헙 워크 플로우에서 secret에 접근 토큰이 등록되어 있다면 자동으로 인증되서 문제없이 설치될 것이다. 

로컬의 경우에는 따로, 패키지 접근 설치를 하려면 패키지 인증을 거쳐야한다. 

 

터미널에 다음 명령어를 입력해서 인증을 받도록 한다.

npm config set //npm.pkg.github.com/:_authToken=개인접근키

 

2. 패키지 다운로드 

package.json에 다음 내용을 추가후, yarn install 실행

{
  "dependencies": {
    "@깃헙원격지이름/vue-crrorropper": "배포한 패키지 버전 정보",
    // ...
  }  
}

 

3. 나의 경우, Nuxt 프로젝트였기 때문에, 플러그인에 추가해서 사용함.

{
  // ...
  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    // ...
    '~/plugins/crrorropper.client.js',
  ], 
}

 


해결한 이슈

문제1 - 스타일이 적용 안 됨.

해결방법 - 패키지 배포할 때, package.json에서 main 프로퍼티에 설정한 파일 1번 줄에 require('./패키지명.common.css')를 추가해서 해결함.

 

문제2 - 사용하는 프로젝트 쪽에서 .npmrc에 접근키를 설정해야하나?

해결방법 - 일단, 사용하는 프로젝트 쪽에 access_token을 설정해 줌.

 

문제3 - 만든 패키지에서 크로퍼(외부 패키지)를 적용하고 난 후에, 프로젝트에 적용해보려니까, 에러가 발생함.

원인 - common.js를 main으로하니까 안되었음.

해결방법 - 

~/build/rollup.config.js파일을 만들고 설정해줌.

import commonjs from "@rollup/plugin-commonjs"; // Convert CommonJS modules to ES6
import vue from "rollup-plugin-vue"; // Handle .vue SFC files
import buble from "@rollup/plugin-buble"; // Transpile/polyfill with reasonable browser support
import resolve from "rollup-plugin-node-resolve";
import alias from "@rollup/plugin-alias";
export default {
  input: "src/index.js", // Path relative to package.json
  output: {
    name: "VueCropper",
    exports: "named",
  },
  plugins: [
    commonjs(),
    resolve(),
    alias({ entries: [{ find: /^@\/(.+)/, replacement: "src/$1" }] }),
    vue({
      css: true, // Dynamically inject css as a <style> tag
      compileTemplate: true, // Explicitly convert template to render function
    }),
    buble(), // Transpile to ES5
  ],
};

다음 외부 패키지들을 설치해줘야 함. 터미널에 명령어 실행

yarn add @rollup/plugin-commonjs rollup-plugin-vue @rollup/plugin-buble rollup-plugin-node-resolve @rollup/plugin-alias

 

package.json에 script를 추가

"scripts": {
    "build-lib": "vue-cli-service build --target lib --name vue-cropper src/index.js",
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    👇 여기 4줄을 추가함.
    "build:mb": "yarn build:umd & yarn build:es & yarn build:unpkg",
    "build:umd": "rollup --config build/rollup.config.js --format umd --file dist/vue-cropper.umd.js",
    // 아마 이 아래부분은 필요없음..
    "build:es": "rollup --config build/rollup.config.js --format es --file dist/vue-cropper.esm.js",
    "build:unpkg": "rollup --config build/rollup.config.js --format iife --file dist/vue-cropper.min.js"
  },

package.json에 Main 도 수정함.

{
  // ...
  "main": "dist/vue-cropper.umd.js",
  // ...
}

yarn build:mb 실행 > 깃헙 원격레포에 Push > yarn publish > 사용할 프로젝트에서 패키지 다운로드 > 작동 확인

 

 

문제4 - 아이콘이 롤업되지 않음.

정성스럽게 설정해 놓은 rollup.config.js를 활용해서 롤업을 하고 있지 않기 때문에 발생하는 문제임.

설치 - https://www.npmjs.com/package/@rollup/plugin-image

다음 명령어가 정상적으로 실행될 수 있도록 수정해줌.

"build:umd": "rollup --config build/rollup.config.js --format umd --file dist/vue-cropper.umd.js",

정상 실행되었고, Umd.js와 umd.css가 dist 밑에 생김. 이를 적용해보니 정상적으로 이미지를 불러와졌음.

 

문제5 - 패키지 받은 프로젝트에서 에러가 발생함

에러메시지

[Vue warn]: $attrs is readonly. found in

[Vue warn]: $listeners is readonly.

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "stencilProps"

해결방법

rollup.config.js에 external: ["vue"] 를 추가함.

import commonjs from "@rollup/plugin-commonjs"; // Convert CommonJS modules to ES6
import vue from "rollup-plugin-vue"; // Handle .vue SFC files
import buble from "@rollup/plugin-buble"; // Transpile/polyfill with reasonable browser support
import resolve from "rollup-plugin-node-resolve";
import image from "@rollup/plugin-image";
import alias from "@rollup/plugin-alias";
import css from "rollup-plugin-import-css";
export default {
  input: "src/index.js", // Path relative to package.json
  output: {
    name: "VueCropper",
    exports: "named",
  },
  external: ["vue"], //🛠🛠🛠🛠🛠🛠🛠🛠🛠🛠🛠 추가해줌.🛠🛠🛠🛠🛠🛠🛠🛠🛠🛠
  plugins: [
    vue({
      css: true, // Dynamically inject css as a <style> tag
      compileTemplate: true, // Explicitly convert template to render function
    }),
    commonjs(),
    resolve(),
    image(),
    alias({ vue$: require.resolve("vue/dist/vue.esm.js") }),
    css(),
    buble(), // Transpile to ES5
  ],
};

 


 

참고

https://velog.io/@sian/Vue%EB%A1%9C-%EB%A7%8C%EB%93%A0-Design-system%EC%9D%84-Rollup%EC%9C%BC%EB%A1%9C-%EB%B2%88%EB%93%A4%EB%A7%81-%ED%95%B4%EB%B3%B8-%ED%9B%84%EA%B8%B0

 

Vue로 만든 UI 라이브러리를 Rollup으로 번들링 해본 후기

웹팩으로 번들링 된 디자인시스템을 롤업으로 말아본 후기

velog.io

https://dealicious-inc.github.io/2021/07/28/create-vue-plugin.html

 

Vue Component 말아버리기

Rollup.js로 Vue Component Plugin 만들기

dealicious-inc.github.io

https://velog.io/@rnfh1111/1

 

[Vue] Component NPM에 배포 삽질기

NPM에 첫 배포를 시도해 보았습니다. 완벽하지는 않지만 한글로 된 자료가 많이 없기에 작성해 봅니다. 목표 vue에서 사용 가능한 widget 형식의 modal을 만들어 배포해 보려고 합니다. 환경 작업환경

velog.io

https://dong-queue.tistory.com/71

 

Vue 라이브러리 NPM 배포 및 사이즈 줄이기

vue, vuetify로 웹페이지를 개발하다가 점점 시간이 지나다 보니 공통화해도 괜찮겠다 싶은 부분을 모아 유틸을 만들게 되었습니다. 이 유틸을 하나의 소스에서 사용할 때는 문제가 없었는데 3개정

dong-queue.tistory.com

 

https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-npm-registry

 

Working with the npm registry - GitHub Docs

Limits for published npm versions If you publish over 1,000 npm package versions to GitHub Packages, you may see performance issues and timeouts occur during usage. In the future, to improve performance of the service, you won't be able to publish more tha

docs.github.com

 

728x90

'Node package' 카테고리의 다른 글

[빌드] yarn build할 때, prod env 설정으로 빌드하는 법  (0) 2022.10.26
[]git hook lint-staged  (0) 2022.10.12

댓글