1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

next.jsでantd利用時にModule not foundとなるエラーの対処

Last updated at Posted at 2021-07-08

前提

next.js v11.0.0
node.js v14.16.1
antd v4.16.6

現象と解決方法

わりとまっさらなnext.jsアプリケーションに、antdのgithub readme通りにinstall、importすると、importした箇所でModule not found: Can't resolve 'antd'のエラー。

こちらを参考に、styles/globals.csspages/_app.js に CSSファイルのimportを書いてもエラー。

@import '../node_modules/antd/dist/antd.css';
@import '~antd/dist/antd.css';

// 次のようなエラーが出る。
// Error: Can't resolve '~antd/dist/antd.css' in '/app/styles'

.babelrc とかnext.config.jsとかごにょごにょしていると、どうもwebpackerの挙動が怪しい。。

途中見かけたエラーの例。

# 10 126.6 ./node_modules/antd/dist/antd.css
# 10 126.6 Module parse failed: Unexpected token (13:6)
# 10 126.6 You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
# 9 178.6 ./node_modules/antd/lib/layout/style/index.less
# 9 178.6 Module parse failed: Unexpected character '@' (1:0)
# 9 178.6 You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
# 9 178.6 > @import '../../style/themes/index';
# 9 178.6 | @import '../../style/mixins/index';

解決方法

結論から言うと、webpack5がcompileしてくれてなかった。
next.js v11 からデフォルトでwebpackが4から5になるよう。
next.config.js に以下を追加し、webpack4を使うと、正常に動作した。

// next.config.j
 module.exports = {
   reactStrictMode: true,
+  webpack5: false,
 }

cssファイルの読み込みも必要。

// pages/_app.js
import 'antd/dist/antd.css'

以下の通りやれば良い。
How to use Ant Design in a Next.js project - Kindacode

webpack5対応プラグイン?

そして後からこんなものを見つけてしまったので、落ち着いたら試してみるかな。
webpack5 でうまくいくならこちらが良いかな。
githubのreadmeに載せといてくれ。。
https://www.npmjs.com/package/next-plugin-antd-less

webpack5とかnext.js11とかのメモ

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?