LoginSignup
6
0

More than 1 year has passed since last update.

ReferenceError: exports is not defined の解決メモ

Last updated at Posted at 2022-03-02

概要

(フロントエンドではない)Typescriptをローカルで触りたく...
Hello Worldができて次にfetchを使いたかっただけなのに、異常にハマってしまったためメモ。

初めて投稿するため、もし問題などあればご指摘いただけると幸いです。

環境

Mac OS Monterey 12.2.1
tsc(typescript) v4.3.4

出たエラー(実行時エラー)

$ node dist/index.js
file:///Users/myuser/~~~~~/dist/index.js:2
Object.defineProperty(exports, "__esModule", { value: true });
                      ^

ReferenceError: exports is not defined

解決方法

tsconfig.json から "module":"commonjs",を削除
のみ。

参考:teratail > typescriptを使用して、Import exportしたいです。

どうしてそれでいいのか、"module":"commonjs",が必要な場合はどうしたらいいのか...は、まだ分かりません。
いつか理解できる時が来たら追記したいと思っています。

実行したかったプログラム、tsconfig.json

  • src/index.ts
import fetch from "node-fetch";

const hello: string = 'Hello, world!'
console.log(hello)

async function getData(url = '') {
    const response = await fetch(url, {
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        headers: {
                (〜省略〜)
        },
    })
    return response.json(); // JSON のレスポンスをネイティブの JavaScript オブジェクトに解釈
}

// JSONの取得
getData('https://(〜あるAPIを呼び出したかった〜)')
  .then(data => {
    console.log(data); // `data.json()` の呼び出しで解釈された JSON データ
}); 

プログラムの参考というか引用元:mdn web docs > Fetch の使用#リクエストオプションの適用

  • tsconfig.json
{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs", // ★★★ ここを消したら動いた ★★★
    "lib": ["es2020"],
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "src",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["dist", "node_modules"],
  "compileOnSave": false
}

tsconfigの参考というか引用元:サバイバルTypeScript > tsconfig.jsonを設定する

6
0
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
6
0