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

背景

	前端项目需要一套同构方案的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 样式入口文件
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Ant Design 的样式中,`.ant-tag-checkable-checked` 的样式是通过 `:before` 伪元素来实现的。这种情况下,我们需要使用 `::before` 伪元素选择器来覆盖默认的样式。 下面是一个简单的示例,展示如何使用 `::before` 伪元素选择器来修改 `CheckableTag` 组件的样式: ```less // index.module.less @import "~antd/dist/antd.less"; // 引入 antd 样式文件 // 自定义样式 .custom-tag { &.ant-tag-checkable-checked::before { background-color: red; // 修改选中状态下的背景色 } } ``` 在上面的代码中,我们首先引入Ant Design 的样式文件。然后,我们定义了一个 `.custom-tag` 样式类,用于修改 `CheckableTag` 组件的样式。 在 `.custom-tag` 样式类中,我们使用 `&.ant-tag-checkable-checked::before` 选择器来选中选中状态下的伪元素,并修改其背景色。 最后,我们将 `.custom-tag` 样式类应用到 `CheckableTag` 组件上即可: ```jsx import { CheckableTag } from 'antd'; import styles from './index.module.less'; function MyComponent() { return ( <div> <CheckableTag className={styles['custom-tag']}>Tag 1</CheckableTag> <CheckableTag className={styles['custom-tag']}>Tag 2</CheckableTag> </div> ); } ``` 在上面的代码中,我们使用 `className` 属性将 `.custom-tag` 样式类应用到 `CheckableTag` 组件上,从而修改其样式。 需要注意的是,为了确保样式生效,我们需要使用 `less-loader` 或者 `css-loader` 中的 `modules` 选项来启用 CSS 模块化。同时,为了避免样式冲突,建议使用类似于 `styles['custom-tag']` 的方式来引用样式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值