前提
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.css
や pages/_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とかのメモ
-
babel-plugin-import - npm
このプラグインはトラップだった。。 -
webpack5 | Next.js
@zeit/next-css / @zeit/next-sass のpackageが非推奨になったよう。 - Next.js 10.0.6以降のwebpack5設定方法
- Upgrade Guide | Next.js
- Next.js の Ver.11 で発表された新機能を1分で読めるまとめ | fwywd(フュード)