如何使用 Antd/Less 和 Sass/CSS 模块配置 Next.js [英] How to configure Next.js with Antd / Less and Sass / CSS modules
问题描述
我想将 Next.js 与 Sass 和 CSS 模块一起使用,但也想使用 Ant Design 并希望使用 Less 样式来实现更小的建筑尺寸.
I want to use Next.js with Sass and CSS modules but also want to use Ant Design and wanted to use the Less styles for smaller building size.
我可以启用 CSS 模块或 Less 加载程序,但不能同时启用.Next.js 中的示例并没有帮助我解决这个问题.
I'm able to enable either CSS modules or Less loader but not both at the same time. The examples from Next.js were not helping me complete that problem.
推荐答案
经过几个小时的研究,我现在终于找到了正确的解决方案,并想分享它:
After multiple hours of research I found now finally the right solution and wanted to share it:
.babelrc
(这里没有魔法)
{
"presets": ["next/babel"],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": true
}
]
]
}
next.config.js
:
/* eslint-disable */
const withLess = require('@zeit/next-less');
const withSass = require('@zeit/next-sass');
const lessToJS = require('less-vars-to-js');
const fs = require('fs');
const path = require('path');
// Where your antd-custom.less file lives
const themeVariables = lessToJS(
fs.readFileSync(path.resolve(__dirname, './assets/antd-custom.less'), 'utf8')
);
module.exports = withSass({
cssModules: true,
...withLess({
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: themeVariables, // make your antd custom effective
importLoaders: 0
},
cssLoaderOptions: {
importLoaders: 3,
localIdentName: '[local]___[hash:base64:5]'
},
webpack: (config, { isServer }) => {
//Make Ant styles work with less
if (isServer) {
const antStyles = /antd\/.*?\/style.*?/;
const origExternals = [...config.externals];
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback();
if (typeof origExternals[0] === 'function') {
origExternals[0](context, request, callback);
} else {
callback();
}
},
...(typeof origExternals[0] === 'function' ? [] : origExternals)
];
config.module.rules.unshift({
test: antStyles,
use: 'null-loader'
});
}
return config;
}
})
});
关于如何编写 withSass
withLess
使用以及如何将 cssModules: true
放在外部对象中的最后提示来自此注释 此处.
The final hint how to write the withSass
withLess
use and to put the cssModules: true
in the outer object came from this comment here.
虽然我已经在尝试从之前的示例中得出的不同组合:next+ant+lessnext+sass
While I was already trying different combinations derived from the examples before: next+ant+less next+sass
为了在此处完成我的 package.json
中的依赖项:
For completion here the dependencies in my package.json
:
...
"dependencies": {
"@zeit/next-less": "^1.0.1",
"@zeit/next-sass": "^1.0.1",
"antd": "^4.1.3",
"babel-plugin-import": "^1.13.0",
"less": "^3.11.1",
"less-vars-to-js": "^1.3.0",
"next": "^9.3.4",
"node-sass": "^4.13.1",
"null-loader": "^3.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sass": "^1.26.3"
}
...
我希望这有助于其他人更快地找到此解决方案.:)
I hope this helps other people to find this solution faster. :)
这篇关于如何使用 Antd/Less 和 Sass/CSS 模块配置 Next.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!