參考:https://www.yuque.com/steven-kkr5g/aza/ig3x9w
Next.js 配合使用antd、less (Integration with Antd)
這個配置配置在NEXT.js和ANTD的官方都有涉及,這個官方的@zeit/next-less組件是不適合直接使用antd配置的,問的人很多,沒有實際的代碼。所以我們寫一下。
1. 問題列舉/Issues in antd & next.js(@zeit/next-less)
Antd的問題
Issues in Antd:
-
antd 如何連接 nextjs #12255 Link (https://github.com/ant-design/ant-design/issues/12255)
-
Antd and Next.js integration #11917 Link(https://github.com/ant-design/ant-design/issues/11917)
Next.js的問題
Issues in Next.js
-
How to Next.js and Antd integration ? #5180 Link(https://github.com/zeit/next.js/issues/5180)
2.安裝支持(Intall @/zeit/next-css & babel-plugin-import)
沒有看錯,你需要先安裝next-css而不是next-less,因爲:我們要拋棄next-less這個官方組件。
還有按需加載的組件babel-plugin-import.
yarn add @zeit/next-css babel-plugin-import
||
npm install @zeit/next-css babel-plugin-import --save-dev
2. 修改babelrc (add .babelrc file in your project)
{
"presets": [
"next/babel"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory":"lib",
"style": true
}
]
]
}
3.增加next-less.config.js(add next-less.config.js file in your project)
const cssLoaderConfig = require('@zeit/next-css/css-loader-config')
module.exports = (nextConfig = {}) => {
return Object.assign({}, nextConfig, {
webpack(config, options) {
if (!options.defaultLoaders) {
throw new Error(
'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade'
)
}
const { dev, isServer } = options
const {
cssModules,
cssLoaderOptions,
postcssLoaderOptions,
lessLoaderOptions = {}
} = nextConfig
options.defaultLoaders.less = cssLoaderConfig(config, {
extensions: ['less'],
cssModules,
cssLoaderOptions,
postcssLoaderOptions,
dev,
isServer,
loaders: [
{
loader: 'less-loader',
options: lessLoaderOptions
}
]
})
config.module.rules.push({
test: /\.less$/,
exclude: /node_modules/,
use: options.defaultLoaders.less
})
// 我們禁用了antd的cssModules
config.module.rules.push({
test: /\.less$/,
include: /node_modules/,
use: cssLoaderConfig(config, {
extensions: ['less'],
cssModules:false,
cssLoaderOptions:{},
dev,
isServer,
loaders: [
{
loader: 'less-loader',
options: lessLoaderOptions
}
]
})
})
if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options)
}
return config
}
})
}
4. 修改next.config.js (change your next.config.js file)
注意modifyvars需要自己定義。Modify files should be defined by yourself。
const withLessExcludeAntd = require("./next-less.config.js")
// choose your own modifyVars
const modifyVars = require("./utils/modifyVars")
if (typeof require !== 'undefined') {
require.extensions['.less'] = (file) => {}
}
module.exports = withLessExcludeAntd({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
},
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: modifyVars
}
})
現在執行以下項目,看是否可以了呢?:)如果有問題歡迎在下方提出。