如何使用 Antd / Less 和 Sass / CSS 模块配置 Next.js

2024-05-20

我想用Next.js https://nextjs.org/带有 Sass 和 CSS 模块但也想使用蚂蚁设计 https://ant.design/并希望对较小的建筑尺寸使用 Less 样式。

我可以启用 CSS 模块或 Less 加载器,但不能同时启用两者。 Next.js 中的示例并没有帮助我解决这个问题。


Edit:对于当前版本的 next.js 来说,这个答案肯定已经过时了,请检查下面的其他答案。

经过几个小时的研究,我现在终于找到了正确的解决方案并想分享它:

.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外部对象来自此评论here https://github.com/zeit/next.js/issues/5180#issuecomment-500704225.

虽然我已经尝试了从之前的示例中得出的不同组合:下一个+蚂蚁+更少 https://github.com/zeit/next.js/tree/canary/examples/with-ant-design-less 下一个+sass https://github.com/zeit/next.js/tree/canary/examples/with-next-sass

为了完成这里的依赖关系,我的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"
  }
...

我希望这可以帮助其他人更快地找到这个解决方案。 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Antd / Less 和 Sass / CSS 模块配置 Next.js 的相关文章

随机推荐