Next.js+Typescript+Yarn 构建服务端渲染项目(2)

Hi,在上一次分享的基础上,我们今天来了解下UI组件antd在该项目中的使用吧

1. 引入Antd组件&babel-plugin-import。

yarn add antd babel-plugin-import -D

在这里插入图片描述z

2. 配置config

  • 新建一个next.config.js,并引入next的css处理withCss模块;

解决不能引入css,只能使用<style jsx>的问题

const withCss = require('@zeit/next-css');

if (typeof require !== 'undefined') {
  require.extensions['.css'] = file => { };
}

module.exports = withCss({});

  • 根目录新建 .babelrc 文件进行antd的相关配置
{
  "presets": [
    "next/babel"
  ], // Next.js的配置文件,相当于继承了它本身的所有配置
  "plugins": [ // 增加新的插件,这个插件就是让antd可以按需引入,包括css
    [
      "import",
      {
        "libraryName": "antd",
        "style": "css" // 引入css
      }
    ]
  ]
}
  • 页面中引入antd组件,并重启
import { Button } from "antd";
const Home = () => (
    <div>
        <Button>click Me</Button>
        hello world
    </div>
);

以上操作结束后,访问 http://localhost:3000/
ok, antd引入。

3. antd拓展补充

以上的操作可以使antd在开发环境上成功加载,but…生产环境下build的时候可能会有bug出现,处理如下

next.config.js

const fs = require('fs');
const path = require('path');
const lessToJS = require('less-vars-to-js');
const withAntd = require('./confs/next-antd.config');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');


if (typeof require !== 'undefined') {
  require.extensions['.less'] = file => { };
}

const antdVariables = lessToJS(
  fs.readFileSync(path.resolve(__dirname, './static/antd-conf.less'), 'utf8')
);


module.exports = withAntd({
  cssModules: true,
  cssLoaderOptions: {
    sourceMap: false,
    importLoaders: 1,
  },
  lessLoaderOptions: {
    javascriptEnabled: true,
    modifyVars: antdVariables,
  },
  webpack: config => {
    config.plugins.push(
      new FilterWarningsPlugin({
        // ignore ANTD chunk styles [mini-css-extract-plugin] warning
        exclude: /mini-css-extract-plugin[^]*Conflicting order between:/,
      }),
    );

    return config;
  },
});

/conf/next-antd.config.js

const cssLoaderConfig = require('@zeit/next-css/css-loader-config');

module.exports = (nextConfig = {}) => ({
  ...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;

      // for all less in clint
      const baseLessConfig = {
        extensions: ['less'],
        cssModules,
        cssLoaderOptions,
        postcssLoaderOptions,
        dev,
        isServer,
        loaders: [
          {
            loader: 'less-loader',
            options: lessLoaderOptions,
          },
        ],
      };

      config.module.rules.push({
        test: /\.less$/,
        exclude: /node_modules/,
        use: cssLoaderConfig(config, baseLessConfig),
      });

      // for antd less in client
      const antdLessConfig = {
        ...baseLessConfig,
        ...{ cssModules: false, cssLoaderOptions: {}, postcssLoaderOptions: {} },
      };

      config.module.rules.push({
        test: /\.less$/,
        include: /node_modules/,
        use: cssLoaderConfig(config, antdLessConfig),
      });

      // for antd less in server (yarn build)
      if (isServer) {
        const antdStyles = /antd\/.*?\/style.*?/;
        const rawExternals = [...config.externals];

        config.externals = [
          (context, request, callback) => {
            if (request.match(antdStyles)) {
              return callback();
            }

            if (typeof rawExternals[0] === 'function') {
              rawExternals[0](context, request, callback);
            } else {
              callback();
            }
          },
          ...(typeof rawExternals[0] === 'function' ? [] : rawExternals),
        ];

        config.module.rules.unshift({
          test: antdStyles,
          use: 'null-loader',
        });
      }

      if (typeof nextConfig.webpack === 'function') {
        return nextConfig.webpack(config, options);
      }

      return config;
    },
  },
});

完整代码地址: https://github.com/qk0728/next-ts.git

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值