LoginSignup
3
1

More than 1 year has passed since last update.

npm パッケージを TypeScript で作って GitHub packeges に公開する

Last updated at Posted at 2021-12-10

LIGHTz アドベントカレンダーの 10日目でございます :clap:
私は :snake: エンジニアですが、TypeScript に挑戦するチャンスをもらいました。
LIGHTz フロントを TypeScript で実装する事が多いので、 TypeScript エンジニアとして駆け出していきます :runner:

※ こちらの記事の前半(ローカルにパッケージを作成する過程まで)はこちらの記事を改変した写経です。(感謝)
https://zenn.dev/sprout2000/books/9325fe6c9c1ba9/viewer/14358
GitHub packeges に公開する過程は公式ドキュメントに倣いました。

こちらの記事で実際に作成したパッケージはGitHubに置いてあります。

npm パッケージ の作成

npm パッケージ 最初の準備

  • GitHub リポジトリを作成する
  • npm init で必要事項を埋める
  • npm install -D typescript ts-node @types/node

ts config の作成

  • ./node_modules/typescript/bin/tsc --init
  • target には ESNext を指定
  • ES モジュールを作成したいので module には ESNext を指定
  • outDir を dist に指定
  • "declaration": true を指定
    • 型定義ファイルが欲しいので
  • "declarationMap": true を指定

npm script を組み立てる

  • npm install -D rimraf
  • 2 つの script を追加
    • "prebuild": "rimraf dist"
    • "build" : "tsc"

ソースコードの用意

  • src/index.ts に文字列 hello を返す関数を export 付きで定義する
  • src/usehello を返す関数を使用する
  • ts-node で実行してみる
$ ./node_modules/.bin/ts-node src/use.ts 
hello

build

  • packege.json の module を記載
    • dist/index.js を記載
  • packege.json の files を記載
    • dist を記載
  • package.json の types を記載
    • dist/index.d.ts
  • npm run build を実行する
    • dist に index.d.ts index.d.ts.map index.js が作成されている事を確認する

npm pack する

  • npm pack --dry-run dry run をして確認をする
  • npm pack する

GitHub packeges に pubulish 編

GitHub packeges に pubulish する

  • GitHub の PAT を用意する
    • 権限はこちらを指定します
      • スクリーンショット 2021-12-04 23.41.20.png
  • GitHub の npm packages に login する
    • npm login --scope=@OWNER --registry=https://npm.pkg.github.com
    • > OWNERを、プロジェクトを含むリポジトリを所有するユーザもしくはOrganizationアカウント名で置き換えてください。
  • package.json のpackege の名前を変更する
    • > デフォルトでは、GitHub Packages は package.json ファイルの name フィールドで指定した GitHub リポジトリにパッケージを公開します。たとえば、@my-org/test という名前のパッケージを my-org/test GitHub リポジトリに公開します。
  • .npmrc を追加する
    • @OWNER:registry=https://npm.pkg.github.com を記載
    • > OWNERを、プロジェクトを含むリポジトリを所有するユーザもしくはOrganizationアカウント名で置き換えてください。
  • npm publish する
  • どうやら上手く publish できたみたいです
    • スクリーンショット 2021-12-05 0.04.53.png

npm packege を install してみる

  • "GitHub packeges に pubulish する" で作成した .npmrc をコピーしてくる
  • npm install してみる
$ npm install @nnashiki/lib_ts_npm_helloworld
+ @nnashiki/lib_ts_npm_helloworld@1.0.0
added 1 package from 1 contributor and audited 2 packages in 0.753s
found 0 vulnerabilities

無事 registory から install することができました :beers:

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1