4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

テスト中に下記のような警告が出たため、その原因についてメモしました。

この警告文は、「TypeScriptの設定ファイル(通常は tsconfig.json)において、 esModuleInterop を true に設定することを検討すべき」 という意味になります。

ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting esModuleInterop to true in your TypeScript configuration file (usually tsconfig.json). 
See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.

原因

なぜesModuleInterop を true に設定する必要があるのかというと、
CommonJSとESモジュールの違いをうまく取り扱うためです。

・CommonJSモジュールとは

主にNode.js環境で使われています。
他ファイルからコードを参照するときはrequire、他ファイルから参照可能にしたいときはmodule.exportsを使用します。

// math.js
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b
};

// main.js
const math = require('./math');
console.log(math.add(2, 3)); // 結果: 5

・ESモジュールとは

他ファイルからコードを参照するときはimport、他ファイルから参照可能にしたいときはexportを使用します。

// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// main.js
import { add, subtract } from './math';
console.log(add(2, 3)); // 結果: 5

esModuleInterop を true に設定すると・・

Node.jsの標準モジュールや多くの既存のライブラリはCommonJS形式で提供されているのですが、これをESモジュール形式でインポートしても使えるようになります。

さらにかみ砕くと、インポート形式をESモジュール形式に勝手に統一してくれるので、開発者は両者の違いをあまり意識せずに済みます。

設定方法

書くまでもないかもしれませんが、、
esModuleInterop を true に設定する場合は設定ファイル(tsconfig.json)に下記を追記します。

{
  "compilerOptions": {
    "esModuleInterop": true,
  }

おわりに

無意識にESモジュールを使用していたので、このような違いがあることを理解していませんでした。
誰かの一助となれば幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?