Typescript

Typescript関連のメモ

セットアップ

npm install -g typescript

vi package.json

↓マージする

  "scripts": {
    "build": "tsc --project tsconfig.json",
    "watch": "tsc --project tsconfig.json --watch"
  },

tsconfig.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDir": "./src",
    "outDir": "./dist",
    "baseUrl": "./src",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "typeRoots": ["types", "node_modules/@types"]
  }
}

./src 配下に .ts ファイルを作成してコードを書く

Imagmein 8

Imagmein 8 を利用しようとして発生したエラー

/path-to/dist/main/helpers/imageConverter.js:18
const imagemin_1 = __importDefault(require("imagemin"));
                                   ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /path-to/node_modules/imagemin/index.js from /path-to/dist/main/helpers/imageConverter.js not supported.
Instead change the require of index.js in /path-to/dist/main/helpers/imageConverter.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/path-to/dist/index.js:36:16) {
  code: 'ERR_REQUIRE_ESM'

Javascript / Typescript 関連に精通していないと CmmonJS や ES の関係性には毎回躓きがち。 tsconfig.jsonpackage.json の設定項目も何がベスプラなのか混乱しがち。

tsconfig は以下のレポジトリに推奨コンフィグがあるので非常に目安になる。

tsconfig/bases: Hosts TSConfigs to extend in a TypeScript app, tuned to a particular runtime environment

TypeScriptの設定の良し悪し

TypeScriptの設定の良し悪し

TypeScriptの設定の良し悪し. GitHub Gist: instantly share code, notes, and snippets.

CommonJS (CJS) と ESM (MJS)の良し悪し

非Javascript専門家としては、CommonJS や ESM に関する歴史的背景などの概要を理解することはできても、それを細部まで理解するにはあまりにも複雑すぎな印象。昨今、ESMしかサポートしない npm モジュールが登場しているが、その意図については分からなかったが、以下の p-limit モジュールでのドキュメントおよびディスカッションのスレッドを読むことで、製作者側から見た ESM 化の意図の一例を把握することができる。

Pure ESM package

Pure ESM package

Pure ESM package. GitHub Gist: instantly share code, notes, and snippets.

  • 多くの作者は事実上として ESM で開発していて(コードを持っていて)、CJS の提供はトランスパイラにかなり依存している。実態として開発者自身が CJS のことを分かっていないケースの方が圧倒的に多く、たまたま動いているだけとも言える

eslint

fork:

GitHub - un-es/eslint-plugin-i: A fork of `eslint-plugin-import` using `get-tsconfig` to replace `tsconfig-paths` and heavy `typescript` under the hood.

GitHub - un-es/eslint-plugin-i: A fork of `eslint-plugin-import` using `get-tsconfig` to replace `tsconfig-paths` and heavy `typescript` under the hood.

A fork of `eslint-plugin-import` using `get-tsconfig` to replace `tsconfig-paths` and heavy `typescript` under the hood. - …

eslint

ファイル全体を無効化する

// @ts-nocheck
/* eslint-disable */

// ... code

/* eslint-enable */


/* eslint-disable @typescript-eslint/no-explicit-any */