URCloud

/ 0评 / 2/ 最后更新:2022-02-15
angular8 自定义webpack,postcss移动端适配

移动端适配往往使用vw,rem等单位,一般配合postcss使用
angular8官方文档中并没有提及自定义webpack的修改,不过好在有个第三方模块可以帮助我们自定义webpack
第一步安装 npm i @angular-builders/custom-webpack --save-dev
第二步修改angular.json

 "architect": {
  ...
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
         "path": "./webpack.config.js"
      },
      ...
    }
  },
  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    "options": {
      "browserTarget": "my-project:build"
    }
  }

第三步在根目录下面新建webpack.config.js

const path = require("path");
const SpritesmithPlugin = require("webpack-spritesmith");

// postcss插件
const postcssLoader = {
  loader: "postcss-loader",
  options: {
    ident: "postcss",
    syntax: "postcss-less",
    plugins: () => [
      require("postcss-px-to-viewport")({
        viewportWidth: 375, // 视窗的宽度,对应的是我们设计稿的宽度,一般是750
        viewportHeight: 667, // 视窗的高度,根据750设备的宽度来指定,一般指定1334,也可以不配置
        unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数
        viewportUnit: "vw", //指定需要转换成的视窗单位,建议使用vw
        selectorBlackList: [".ignore"], // 指定不转换为视窗单位的类,可以自定义,可以无限添加,建议定义一至两个通用的类名
        minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
        mediaQuery: false
      }),
      require("autoprefixer")({
        overrideBrowserslist: [
          "Android 4.1",
          "iOS 7.1",
          "Chrome > 31",
          "ff > 31",
          "ie >= 8"
        ],
        grid: true
      })
    ]
  }
};

// 雪碧图插件
const spritePlugin = new SpritesmithPlugin({
  src: {
    cwd: path.resolve(__dirname, "src/assets/images"),
    glob: "*.png"
  },
  target: {
    image: path.resolve(__dirname, "src/assets/sprite.png"),
    css: [
      path.resolve(__dirname, "src/assets/sprite.css"),
      [
        path.resolve(__dirname, "src/assets/sprite.json"),
        { format: "json_texture" }
      ]
    ]
  },
  apiOptions: {
    cssImageRef: "assets/sprite.png"
  }
});

module.exports = (config, options) => {
  // config就是系统的webpack配置
  // 第一步过滤掉系统的css和less处理

  config.module.rules = config.module.rules.filter(
    rule => rule.test.toString() !== "/\\.less$/"
  );

  // 配置自定义的less处理
  config.module.rules.push({
    test: /\.(less)$/,
    exclude: [
      path.resolve(__dirname, "src/styles.less")
    ],
    use: ["raw-loader", postcssLoader, "less-loader"]
  });

  config.module.rules.push({
    test: /\.(less)$/,
    include: [
      path.resolve(__dirname, "src/styles.less")
    ],
    use: ["style-loader", postcssLoader, "less-loader"]
  });

  config.plugins.push(spritePlugin);

  return config;
};

在webpack的配置中,建议先console一下原先的配置,然后根据自己的需求去修改对应的loader,这样不容易出错。

2

Leave a Reply

Your email address will not be published.