这个配置配置在NEXT.js和ANTD的官方都有涉及,这个官方的@zeit/next-less组件是不适合直接使用antd配置的,问的人很多,没有实际的代码。所以我们写一下。
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)
没有看错,你需要先安装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
{
"presets": [
"next/babel"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory":"lib",
"style": true
}
]
]
}
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
}
})
}
注意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
}
})
现在执行以下项目,看是否可以了呢?:)如果有问题欢迎在下方提出。