前提条件
以下の環境でnpm run buildするとError: Cannot find module '@babel/preset-env/lib/utils' Require stack:が出た時の対処法です。
"core-js": "^3.25.3",
"fibers": "^5.0.3",
"nuxt": "^2.13.3",
"vue": "^2.7.10",
"vue-server-renderer": "^2.7.10",
"vue-template-compiler": "^2.7.10"
出たエラーメッセージがこちら
Module build failed (from ./node_modules/babel-loader/lib/index.js): friendly-errors 12:57:45
Error: /Users/Documents/nuxtjs_website/.nuxt/client.js: Cannot find module '@babel/preset-env/lib/utils'
Require stack:
(以下割愛)
@babel/preset-envをインストール
@babel/preset-envをインストールするか、もし既に入っている場合は古いバージョン 7.12.17を使用しましょう。
$ npm install --save-dev @babel/preset-env
nuxt.config.jsを編集
インストールしただけでは以下のエラーが出る場合があります。
WARN Though the "loose" option was set to "false" in your @babel/preset-env config, it will not be used for @babel/plugin-proposal-private-property-in-object since the "loose" mode option was set to "true" for @babel/plugin-proposal-class-properties.
The "loose" option must be the same for @babel/plugin-proposal-class-properties, @babel/plugin-proposal-private-methods and @babel/plugin-proposal-private-property-in-object (when they are enabled): you can silence this warning by explicitly adding
["@babel/plugin-proposal-private-property-in-object", { "loose": true }]
to the "plugins" section of your Babel config.
その場合は、以下の記述をnuxt.config.jsのbuildに追加しましょう。
build: {
babel: {
presets({ isServer }) {
const targets = isServer ? { node: 'current' } : { ie: 11 }
return [
[require.resolve("@babel/preset-env"), { targets }]
]
},
plugins: [
"@babel/syntax-dynamic-import",
"@babel/transform-runtime",
"@babel/transform-async-to-generator"
]
},
}
バージョンアップすれば出ないエラー
どうやらこちらのエラーはNuxt2の古いバージョンで起こるエラーで、Nuxt3では修正されているようです。
可能であればバージョンアップをしてしまうのも手かもしれません。