1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

パッケージ開発でCommonJSとES Modulesの両方に対応する💪 - デュアルパッケージ

Last updated at Posted at 2023-01-13

やりたいこと

パッケージの開発を行うにあたり、CommonJSとES Modulesの両方に対応したい😃

対応方法

CommonJS用とES Modules用の2つのJavaScriptを出力します。
出力するmoduleの分だけtsconfig.jsonを用意します。

以下の4つのファイルを用意します。

./
├── tsconfig.base.json
├── tsconfig.cjs.json
├── tsconfig.esm.json
└── tsconfig.json
tsconfig.json
{
  "extends": "./tsconfig.base.json"
}
tsconfig.base.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "outDir": "./dist/",
    // ...
  },
  // ...
}
tsconfig.cjs.json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "./dist/"
  }
}
tsconfig.esm.json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "module": "esnext",
    "outDir": "./dist/esm"
  }
}

package.jsonに以下の設定を追加します。

package.json
{
  "main": "dist/index.js",
  "module": "dist/esm/index.js",
  "types": "dist/esm/index.d.ts",
  "scripts": {
    "build": "yarn build:cjs && yarn build:esm",
    "build:cjs": "tsc -p tsconfig.cjs.json",
    "build:esm": "tsc -p tsconfig.esm.json",
  }
}
  • main: commonjsのエントリーポイントとなるjsファイルを設定します。
  • module: esmoduleのエントリーポイントとなるjsファイルを設定します。
  • types: 型定義ファイルのエントリーポイントとなるtsファイルを設定します。

これで完成です🤗

参考

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?