3
2

More than 1 year has passed since last update.

imageminをrequireして怒られる

Posted at

はじめに

imageminをnode.jsで実行すると怒られた。

imagemin.js
const imagemin = require('imagemin')
const imageminMozjpeg = require('imagemin-mozjpeg')
const imageminPngquant = require('imagemin-pngquant')

imagemin(...)
const imagemin = require('imagemin')
                 ^
Error [ERR_REQUIRE_ESM]: require() of ES Module
Instead change the require of index.js in imagemin.js to a dynamic import() which is available in all CommonJS modules.

importで読み込んでね」と怒られている。

importで読み込んで実行する。

imagemin.js
import imagemin from 'imagemin'
import imageminMozjpeg from 'imagemin-mozjpeg'
import imageminPngquant from 'imagemin-pngquant'

imagemin(...)
(node:65499) Warning: To load an ES module,
set "type": "module" in the package.json or use the .mjs extension.

再び怒られる。

package.json"type": "module"を追加するか、拡張子を.mjsに変更してね」と言われている。

imagemin.mjs
import imagemin from 'imagemin'
import imageminMozjpeg from 'imagemin-mozjpeg'
import imageminPngquant from 'imagemin-pngquant'

imagemin(...)

done!!

何がどうなっているのか

imageminのv8系からESMのみサポートしている模様。
requireで読み込むことができないのでimportで読み込む必要がある。
また、node.jsで実行するには拡張子を.mjsにするか、packege.json"type": "module"を追加する必要がある。

packege.json"type": "module"を追加するときは注意が必要で、そのプロジェクト内のrequireを全てimportでの読み込みに修正する必要がある。
そうすると__dirnameなどが使えなくなる。

個人的にはESMのパッケージをnode.jsで動かす場合は.mjsにしています。

ESM?

node.js v12からESMをデフォルトでサポートしていた。
nodeのコミュニティでもESMに統一していこうみたいな雰囲気になっている。

ES modulesとCommonJSの話を書くと長くなるので、おすすめの書籍を貼っておきます。
この辺りはJSの歴史を遡って全体像を把握した方が幸せになります。

まとめ

node.jsで実行するライブラリは脳死でrequireしがちだったので色々と勉強になった。

参考資料

3
2
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
3
2