craco.config.js内配置px转rem

527 阅读1分钟

基于"@craco/craco": "^7.0.0-alpha.9"的react开发,

cnpm install babel-plugin-styled-components-px2rem 
const path = require('path');

const CracoLessPlugin = require('craco-less');

const resolve = pathname => path.resolve(__dirname, pathname)
module.exports = {
  devServer: {
    // open: true, // 启动时打开浏览器
    port: 8090, // 端口号
    proxy: { // 接口反向代理
      '/apiProxy': {
        target: '', 
        changeOrigin: true,
        // pathRewrite: (path) => path.replace('/apiProxy', ''),
      },
    },
  },
  // less配置
  plugins: [
    {
      plugin: CracoLessPlugin,
    },
  ],
  // webpack
  webpack: {
    alias: {
      // val值应该是绝对路径,通过path可以将当前文件路径和src路径进行拼接
      '@': resolve('src'),
      'components': resolve('src/components'),
    },
    configure: {
      module:{
        rules: [
          {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: [
              {
                // 行内样式PX转rem
                loader: resolve('src/utils/loaders/jsxPx2RemLoader'),
                options: {
                  remUnit: 16, // 基本单位
                  remFixed: 3, // 保留小数点后位数
                }
              }
            ]
          }
        ],
      }
    }
  },
  babel: {
    plugins: [
      [
        'styled-components-px2rem',
        {
          // 基准值(根元素fontSize): 1rem = 16px
          rootValue: 16,
          // 保留小数点的精度
          unitPrecision: 3,
          minPixelValue: 0,
          multiplier: 1,
          transformRuntime: true
        },
      ],
    ],
  },
}

注意:需要配置package.json文件,并用craco打开项目

"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },