技术探索

Next.js 11.0.x版本+antd使用webpack5的配置方法

2021-07-15
1042

由于next.js仅支持sass,而antd又是用less开发,官方的next-less一直停留在1.01版本,next.js升级到11.0以后的版本默认支持webpack5以上的版本,所以用下面的方法来实现支持webpack5。

next.config.js:

const fs = require('fs');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const lessToJS = require('less-vars-to-js'); 
const themeVariables = lessToJS(fs.readFileSync(path.resolve(__dirname, './antd-custom.less'), 'utf8'));

module.exports = { 
	useFileSystemPublicRoutes: false,
	poweredByHeader: false,
	webpack: (config, { isServer }) => {
		if (isServer) {
			const antStyles = /antd\/.*?\/style.*?/;
			const origExternals = [...config.externals];
			config.externals = [
				(ctx, callback) => {
					if (ctx.request.match(antStyles)) return callback();
					if (typeof origExternals[0] === 'function') {
						return origExternals[0](ctx, callback);
					} else {
						return callback();
					}
				},
				...(typeof origExternals[0] === 'function' ? [] : origExternals),
			];
			config.module.rules.unshift({
				test: antStyles,
				use: 'null-loader',
			});
		}

		config.module.rules.push({
			test: /\.less$/i,
			use: [
				MiniCssExtractPlugin.loader,
				{
					loader: 'css-loader',
					options: {
						importLoaders: 1,
						modules: {
							mode: 'local',
							auto: /\.module\.less/i,
							localIdentName: '__[hash:base64:6]',
						},
					},
				},
				{
					loader: 'less-loader',
					options: {
						lessOptions: {
							javascriptEnabled: true,
							modifyVars: themeVariables,
						},
					},
				},
			],
		});

		config.plugins.push(
			new MiniCssExtractPlugin({
				experimentalUseImportModule: true,
				ignoreOrder: true,
				filename: 'static/css/[name].[contenthash].css',
				chunkFilename: 'static/css/[name].[contenthash].chunk.css',
			})
		);

		config.optimization.minimizer.push(new CssMinimizerPlugin());

		return config;
	},
};