Как добавить antd в Nextjs - PullRequest
       67

Как добавить antd в Nextjs

0 голосов
/ 21 апреля 2020

Я создаю базу проекта на с-ant-design-less и затем пытаюсь добавить sass в проект. Я изменяю следующие файлы:

next.config. js: * пакет 1005 *

/* eslint-disable */
const withSass = require("@zeit/next-sass");
const withLess = require("@zeit/next-less");
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,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: "[folder]_[local]___[hash:base64:5]",
  },
  ...withLess({
    lessLoaderOptions: {
      javascriptEnabled: true,
      modifyVars: themeVariables, // make your antd custom effective
    },
    webpack: (config, { isServer }) => {
      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;
    },
  }),
});

. json

{
  "name": "with-ant-design-less",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@zeit/next-less": "^1.0.1",
    "@zeit/next-sass": "^1.0.1",
    "antd": "^3.5.4",
    "babel-plugin-import": "^1.7.0",
    "less": "3.0.4",
    "less-vars-to-js": "1.3.0",
    "next": "latest",
    "null-loader": "2.0.0",
    "react": "^16.7.0",
    "sass": "^1.26.3",
    "react-dom": "^16.7.0"
  },
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^13.13.1",
    "typescript": "^3.8.3"
  }
}

но при запуске проекта я получить следующую ошибку:

[ error ] ./pages/index.module.scss
To use Next.js' built-in Sass support, you first need to install `sass`.
Run `npm i sass` or `yarn add sass` inside your workspace.

Хотя я ищу лучшее решение для настройки проекта, потому что таким образом все стили будут объединены в один большой кусок, что приведет к проблемам с производительностью.

Есть идеи? Спасибо

1 Ответ

1 голос
/ 22 апреля 2020

next.config. js:

const withPlugins = require('next-compose-plugins');
const withCss = require('@zeit/next-css');
const withSass = require('@zeit/next-sass');
const withLess = require('@zeit/next-less');
const lessToJS = require('less-vars-to-js');
const fs = require('fs');
const path = require('path');

const lessThemeVariablesFilePath = './static/ant-theme-variables.less';

const themeVariables = lessToJS(
  fs.readFileSync(path.resolve(__dirname, lessThemeVariablesFilePath), 'utf8'),
);

const lessNextConfig = {
  lessLoaderOptions: {
    javascriptEnabled: true,
    modifyVars: themeVariables,
  },
  webpack: (config, { isServer }) => {
    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;
  },
};
const sassNextConfig = {
  cssModules: true,
  cssLoaderOptions: {
    localIdentName: '[path]___[local]___[hash:base64:5]',
  },
};

module.exports = withPlugins([
  [withLess, lessNextConfig],
  [withSass, sassNextConfig],
]);

babel config:

module.exports = {
  presets: ['next/babel'],
  plugins: [
    ['import', { libraryName: 'antd', style: true }],
  ],
};

Я использую sass, less и css. это зависит от вашего требования. и вы можете добавить свои пользовательские переменные в файл stati c, как я. надеюсь быть полезным.

...