■ はじめに
https://dk521123.hatenablog.com/entry/2021/01/23/000000
の続き。 Lodash を使う機会がでてきて、新たに仕入れた知識がでてきたので メモしておく。
目次
【1】Lodash の個別インストール 【2】サンプル 1)lodash.uniqby - 重複排除 【3】トラブル 1)エラー「TypeError: lodash_xxxx_1.default is not a function」表示
【1】Lodash の個別インストール
https://dk521123.hatenablog.com/entry/2021/01/23/000000
より抜粋 使用上の注意 * でかいらしい => ただ、個別でインストールできる!
例:lodash.uniqby のみインストールする場合
https://www.npmjs.com/package/lodash.uniqby
npm i --save lodash.uniqby
【2】サンプル
1)lodash.uniqby - 重複排除
import { uniqBy } from 'lodash'; // id = 1, 2, 3, 4, 5 const people = [ {id: 1, name: 'Mike', birthDate: '1922-02-20'}, {id: 5, name: 'Sam', birthDate: '2011-12-09'}, {id: 2, name: 'Kevin', birthDate: '1983-07-10'}, {id: 3, name: 'Tom', birthDate: '1978-01-04'}, {id: 5, name: 'Sam', birthDate: '2011-12-09'}, {id: 4, name: 'Alex', birthDate: '2012-11-23'}, {id: 2, name: 'Kevin', birthDate: '1983-07-10'}, {id: 1, name: 'Mike', birthDate: '1922-02-20'}, {id: 2, name: 'Kevin', birthDate: '1983-07-10'}, {id: 1, name: 'Mike', birthDate: '1922-02-20'}, {id: 5, name: 'Sam', birthDate: '2011-12-09'}, ]; let result = uniqBy<any>(people, 'id'); console.log(result);
出力結果
[ { id: 1, name: 'Mike', birthDate: '1922-02-20' }, { id: 5, name: 'Sam', birthDate: '2011-12-09' }, { id: 2, name: 'Kevin', birthDate: '1983-07-10' }, { id: 3, name: 'Tom', birthDate: '1978-01-04' }, { id: 4, name: 'Alex', birthDate: '2012-11-23' } ]
【3】トラブル
1)エラー「TypeError: lodash_xxxx_1.default is not a function」表示
実行時に以下のエラーでエラー
エラー内容
var result = lodash_uniqby_1["default"](people, 'id'); ^ TypeError: lodash_uniqby_1.default is not a function at Object.<anonymous> (C:\xxxxx\demo.js:17:40) at Module._compile (node:internal/modules/cjs/loader:1108:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) at Module.load (node:internal/modules/cjs/loader:973:32) at Function.Module._load (node:internal/modules/cjs/loader:813:14) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) at node:internal/main/run_main_module:17:47
対応案
【修正前】 import uniqBy from 'lodash.uniqby'; 【修正後】 import { uniqBy } from 'lodash'; or import * as uniqBy from 'lodash/uniqby';
参考文献
https://github.com/lodash/lodash/issues/3542
https://github.com/thymikee/jest-preset-angular/issues/77
より抜粋 ~~~~~~~~~~ import * as isString from 'lodash/isString'; ~~~~~~~~~~
参考文献
https://qiita.com/Hitomi_Nagano/items/d6ce1f4bfb8fbdf3b952
関連記事
TypeScript ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/12/21/180904
Lodash ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2021/01/23/000000