0
2

More than 1 year has passed since last update.

imagemin-mozjpegのバージョンを最新にしたらrequire()のエラーが出てはまった

Posted at

事の発端は軽い気持ちでバージョンを上げただけ

1年ぶりぐらいに手元の開発環境をアップグレードしようと思い何も考えずにバージョンをアップデートしたことが始まりでした。

imageminのビルド時だけエラーが出始める

エラーの内容を適当にコピペして海外サイトとかを徘徊したが、原因が掴めず・・・。

const imageminMozjpeg = require('imagemin-mozjpeg')
                        ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/techthree/projects/tech-three/pug_sass_webpack/node_modules/imagemin-mozjpeg/index.js from /Users/techthree/projects/tech-three/pug_sass_webpack/imagemin.js not supported.
Instead change the require of index.js in /Users/techthree/projects/tech-three/pug_sass_webpack/imagemin.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/techthree/projects/tech-three/pug_sass_webpack/imagemin.js:2:25) {
  code: 'ERR_REQUIRE_ESM'
}

imageminは今から2ヶ月前にアップデートされていた

npmimagemin-mozjpegのバージョンによってimportかrequireか異なっていました。
最新の10系はimport、9系はrequireとなっていました。
ひとまず最新を使用したいのでimportに置換します。


import imagemin from 'imagemin';
import imageminMozjpeg from 'imagemin-mozjpeg';

(async () => {
    await imagemin(['src/assets/img/**/*.jpg'], {
        destination: 'build/images',
        plugins: [
            imageminMozjpeg()
        ]
    });

    console.log('Images optimized');
})();

importにしたら違うエラーが出た!!!

(node:21109) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/techthree/projects/tech-three/pug_sass_webpack/imagemin.js:1
import imagemin from 'imagemin';
^^^^^^

エラーの内容を注視する!!!

ビルド時のエラーメッセージに対処法が記載されていたのでその通りに対処してみます。
この場合はpackage.jsonに "type": "module" を追加します。
私はscriptsの直前に指定しました。

{
  "name": "npmscripts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "watch:imagemin": "onchange src/img/**/*.{jpg,png} -- node imagemin.js {{changed}}",
    "build:imagemin": "node imagemin.js"
  },
  "author": "Tech Three",
  "license": "ISC",
  "devDependencies": {}
}

追加後に再度ビルドを実行するとエラーが出ずに正常に完了することができました!

yarn run v1.22.17
$ node imagemin.js
Images optimized
✨  Done in 0.42s.
0
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
0
2