next框架 引入less、less module ,antd、 ant-mobile,配置postcss.config.js文件对移动端文件做适配处理实践

本文介绍了一种针对PC和移动端的前后端同构方案,通过配置Next.js、Ant Design UI 和 Ant Design Mobile来实现标准样式及响应式布局。文章详细记录了配置过程中的关键步骤和技术要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

	前端项目需要一套同构方案的PC 移动端活动仓库
	需求:- pc 	
			    标准样式 无需缩放 
			    使用antd UI 组件库
		  - 移动端
				使用vw 做适配 
				使用antd-mobile
less less module	

思路

next.config.js 配置文件中处理 less less-module 的用法
pstcss.config.js 文件中处理适配问题

过河

	问题一、

在这里插入图片描述
postcss配置 参数不正确 postcss-loader 版本问题 切换到@3.x 即可

实现

.babelrc 
{
  "presets": ["next/babel"],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "libraryDirectory": "lib",
        "style": true
      }
    ],
    [
      "import",
      {
        "libraryName": "ant-mobile",
         "libraryDirectory": "lib",
         "style": true
      },
      "antd-mobile" //无意义 需要添加一个名字 避免跟antd 冲突报格式错误
    ],
    [
      "import",
      {
        "libraryName": "@ant-design/icons",
        "libraryDirectory": "lib/icons",
        "camel2DashComponentName": false
      },
      "@ant-design/icons"
    ],
    [
      "styled-components",
      {
        "ssr": true
      }
    ]
  ]
}
 添加 postcss.config.js
module.exports = (file) => {
  // antd index.less 不转
  // antd - mobile  index.m.less  转
  // console.log(designWidth, '----designWidth')
  // console.log(path.join('node_modules', 'vant'), '-位置--')

  if (file.file.basename === 'index.m.less' || file.file.basename === 'antd-mobile.less') {
    return {
      "plugins": {
        autoprefixer: {}, // 用来给不同的浏览器自动添加相应前缀,如-webkit-,-moz-等等
        'postcss-px-to-viewport': {
          unitToConvert: 'px', // 要转化的单位
          viewportWidth: 750, // UI设计稿的宽度
          unitPrecision: 6, // 转换后的精度,即小数点位数
          propList: ['*'], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
          viewportUnit: 'vw', // 指定需要转换成的视窗单位,默认vw
          fontViewportUnit: 'vw', // 指定字体需要转换成的视窗单位,默认vw
          // selectorBlackList: ['wrap'], // 指定不转换为视窗单位的类名,
          minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
          mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false
          replace: true, // 是否转换后直接更换属性值
          // exclude: [/node_modules/], // 设置忽略文件,用正则做目录名匹配
          landscape: false, // 是否处理横屏情况
        },
      },
    }
  } else {
    return {
      "plugins": {
        autoprefixer: {}, // 用来给不同的浏览器自动添加相应前缀,如-webkit-,-moz-等等
      },
    }
  }
}
修改 next.config.js
// 如果不要style-components 而是 less,就用这套配置
const webpack = require('webpack')
const cssLoaderConfig = require("@zeit/next-css/css-loader-config")
const lessToJS = require('less-vars-to-js')

const fs = require('fs')
const path = require('path')

const packageJson = require('./package.json')
const projectName = `${packageJson.name}`.replace('-frontend', '')

const __DEV__ = process.env.NODE_ENV === 'development'
const SERVER_ENV = process.env.SERVER_ENV || 'prod';

// Where your antd-custom.less file lives
const themeVariables = lessToJS(
  fs.readFileSync(path.resolve(__dirname, './src/styles/antd-custom.less'), 'utf8')
)


module.exports = {
  distDir: __DEV__ ? './.next' : './dist',
  // 只有生产,才做cdn
  assetPrefix: SERVER_ENV === 'prod' ? `https://xxxxx.xxxxx.com/${projectName}` : '',
  devIndicators: {
    autoPrerender: false
  },
  webpack: (config, { isServer, dev }) => {
    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',
      })

      config.module.rules.push({
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      });
    }

    config.module.rules.push({
      test: /\.(jpe?g|png|gif|ico|svg)$/,
      use: [
        {
          loader: 'url-loader',
          options: {
            esModule: false,
            limit: 8192,
            fallback: 'file-loader',
            publicPath: `/_next/static/images/`,
            outputPath: `/static/images/`,
            name: '[name]-[hash].[ext]'
          }
        }
      ]
    })

    const lessObj = {
      extensions: ["less"],
      dev,
      isServer,
      loaders: [
        {
          loader: "less-loader",
          options: { javascriptEnabled: true, modifyVars: themeVariables },
        },
      ],
    };
    const less = cssLoaderConfig(config, lessObj);
    const moduleless = cssLoaderConfig(config, {
      ...lessObj,
      cssModules: true,
      cssLoaderOptions: {
        importLoaders: 1,
        localIdentName: "[local]___[hash:base64:5]",
      },
    });

    // .less 文件都添加 css module
    config.module.rules.push({
      test: /\.less$/,
      exclude: path.join(__dirname, "node_modules"),
      use: moduleless,
    });

    config.module.rules.push({
      test: /\.less$/,
      include: path.join(__dirname, "node_modules"),
      use: less,
    });

    config.plugins.push(
      new webpack.EnvironmentPlugin([
        'NODE_ENV',
        'SERVER_ENV',
        'PORT',
        'HTTPS',
      ])
    )
    config.resolve.alias['src'] = path.join(__dirname, 'src')
    return config
  },
}

安装

 yarn add postcss-px-to-viewport 
 yarn add antd-mobile
 
_app.js 文件中  引入antd-mobile的全局公共样式 
import "antd-mobile/dist/antd-mobile.less";   // 引入官方提供的 less 样式入口文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值