ごった煮

色々な事を書いてます

TypeScript でライブラリを作り始めるときの個人的準備-2022-07

最近数カ月に一回程度の頻度で、TypeScript のライブラリを書く機会があるのですが、毎回初期のセットアップを忘れているので、 備忘録として残します。

※ フロントエンドは、ほぼ素人なので、もっと良い方法を知っている方がいましたら、是非教えてください。

開発環境の前提条件

VSCode Dev container でコンテナの環境を立ち上げる

ts で開発する際、Windows の環境を極力汚したくないので、VSCode の Dev container を使用します。

VSCode を開き、ctrl + shift + p でコマンドパレットを開きます。

コマンドパレットで devcontainer 等と入れると、 Remote-Containers: Add Development Container Configuration Files... が表示されるので、そちらを選択します。

コンテナの種別を聞かれるので、Node.js & TypeScript を選択します。

お好みの Node.js のバージョンを選択

今回は、デフォルトの 16-bullseye を選択します。

その他、入れたいツールを選択します。

今回は、特に何もいれませんでした。

これで、Dev container の設定ファイルが生成されます。

設定ファイルが生成されると、右下に、コンテナでフォルダを開きなおすか聞かれるので

Reopen in Container を選択して、コンテナでフォルダを開きなおします。

VSCode が再起動すると、フォルダがコンテナ内で開かれている状態になります。

ctrl + shift + ` でターミナルを開きます。

これで、コンテナ内に初期の環境が立ち上がりました。

TypeScript をインストール

yarn add typescript --dev

yarn run tsc--init

これで、TypeScript のインストール + デフォルトの tsconfig.json の生成が出来ました。

tsconfig.json を設定する

こんな感じ

{
  "compilerOptions": {
    "target": "ESNext",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

jest のインストール

書いたコードを動かすのに色々するのも面倒なので、初めにテストフレームワークとして jest を入れます

yarn add jest ts-jest @types/jest --dev

jest の設定を追加する

依存関係は、

{
  "devDependencies": {
      ~省略~
  },
  "browser": "dist/index.js",
  "scripts": {
    "build": "rollup -c",
    "test": "jest"
  },
  "jest": {
    "moduleFileExtensions": [
      "ts",
      "js"
    ],
    "transform": {
      "^.+\\.ts$": "ts-jest"
    },
    "globals": {
      "ts-jest": {
        "tsConfig": "tsconfig.json"
      }
    },
    "testMatch": [
      "**/test/*.test.ts"
    ]
  },
  "dependencies": {
       ~省略~
  }
}

jest を動かしてみる

サンプルコードを作る

src というフォルダを作り、index.ts を作成

function hello(text: string) {
    return `hello ${text}`
}

export {
    hello
}

テストコードを作る

test というフォルダを作り、hello.test.ts を作成

import { hello } from '../src/index'

describe('hello test', (): void => {
    test('text', (): void => {
        const response = hello('world')

        expect(response).toBe('hello world')
    })
})

コマンドラインで、yarn test を実行

テストがパスしたら、設定完了です

rollup.js を導入する

色々入れるものがあるので、下のものを yarn でインストール

yarn add rollup rollup-plugin-terser @rollup/plugin-babel @rollup/plugin-commonjs @rollup/plugin-node-resolve @rollup/plugin-typescript tslib --dev

rollup.config.js を設定する

ルートフォルダに rollup.config.js を作成します。

minify したものと、minify してないものを出力する設定になっています。

import pluginTypescript from "@rollup/plugin-typescript"
import pluginNodeResolve from "@rollup/plugin-node-resolve"
import { terser as pluginTerser, terser } from "rollup-plugin-terser"
import pluginCommonjs from "@rollup/plugin-commonjs"

import pkg from './package.json'

export default {
    input: 'src/index.ts',
    output: [
        {
            name: 'index.js',
            file: pkg.browser,
            format: 'iife',
            sourcemap: 'inline'
        },
        {
            name: 'index.js',
            file: pkg.browser.replace('.js', '.min.js'),
            format: 'iife',
            plugins: [
                terser()
            ]
        }
    ],
    plugins: [
        pluginTypescript(),
        pluginCommonjs({
            extensions: [
                ".js",
                ".ts"
            ]
        }),
        pluginNodeResolve({
            browser: true
        })
    ]
}

ビルドしてみる

yarn build でビルドされます。

dist フォルダに、index.jsindex.min.js が出力されたら成功です。

まとめ

IDE とかでさっくり作れればいいのですが、中々そういうわけにもいかず悩ましい所ですね。

IE11 が退役したので、小規模なプロジェクトならもう babel やらは不要かなということで 今回 babel は、入れていません。