webpack5 使用svg asset-module

作者: xxxsjan | 来源:发表于2022-04-18 21:06 被阅读0次
  • webpack5 已经废弃了url-loader

  • webpack5自带的asset-module就可以实现以前的功能

  • asset-module整合了原本的url-loader、file-loader、raw-loader

通过type属性设置使用对应之前loader的功能

type: "asset/resource"

---将资源分割为单独的文件,并导出url,就是之前的 file-loader的功能.

type: "asset/inline"

---将资源导出为dataURL(url(data:))的形式,之前的 url-loader的功能.

type: "asset/source"

---将资源导出为源码(source code). 之前的 raw-loader 功能.

type: "asset"

---自动选择导出为单独文件或者 dataURL形式(默认为8KB)
---之前有url-loader设置asset size limit 限制实现。

{
  test: /\.(svg)$/,
  type: "asset/source",
  generator: {
  // 打包到 dist/image 文件下
  filename: "images/[contenthash][ext][query]",
  },
},
{
  test: /\.(png|jpe?g|gif|webp)$/,
  type: "asset", 
  parser: {
  // 转base64的条件
  dataUrlCondition: {
  maxSize: 25 * 1024, // 25kb
  },
  },
  generator: { 
  filename: "images/[contenthash][ext][query]",
  },
}

测试使用

<template>
  <div class="box">
    <h1>我是App哈哈哈哈</h1>
    <div id="svg"></div>
  </div>
</template>

<script>
import svgContent from "./icons/svg/chart.svg";

export default {
  mounted() {
    window.document.getElementById("svg").innerHTML = svgContent;
  },
};
</script>

<style lang="scss">
.box {
  width: 500px;
  height: 200px;
  color: orange;
  // background-color: #000;
}
</style>

效果↓↓↓


image.png

假如上面svg type改为asset,他会把我刚刚的svg转base64
因为默认8k以下就转,
也可以手动配置,parser里的dataUrlCondition即可设置

{
        test: /\.(png|jpe?g|gif|webp|svg)$/,
        type: "asset",
        // parser: {
        //   // 转base64的条件
        //   dataUrlCondition: {
        //     maxSize: 25 * 1024, // 25kb
        //   },
        // },
        generator: {
          // 打包到 dist/image 文件下
          filename: "images/[contenthash][ext][query]",
        },
},

效果↓↓↓


image.png

相关文章

网友评论

    本文标题:webpack5 使用svg asset-module

    本文链接:https://www.haomeiwen.com/subject/uhqjertx.html