Skip to content

webpack5 笔记二,处理图片、字体、数据

动手

新增依赖

shell
npm install --save-dev style-loader css-loader

增加 webpack loader

js
 {
   test: /\.(png|svg|jpg|jpeg|gif)$/i,
   type: 'asset/resource'
 },
 {
   test: /\.(woff|woff2|eot|ttf|otf)$/i,
   type: 'asset/resource'
 }

测试图片

经过测试,不会报错。

方式一:

js
import love from './assets/img/love1.png'
js
constimg = new Image();
img.src = love
box.appendChild(img)

方式二:

js
  const el2 = document.createElement('div')
  el2.innerHTML = _.join(['头大'])
  el2.classList.add('square')
  box.appendChild(el2)
css
.square {
  width: 100px;
  height: 100px;
  background-image: url(../img/love1.png);
}

测试字体图标

经过测试,也是可行的。

js
  const el3 = document.createElement('div')
  el3.className = 'my-icon iconfont icon-dianhuatianchong'
  box.appendChild(el3)

  const el4 = document.createElement('div')
  el4.className = 'my-icon iconfont icon-a-youjianchakanyoujianfasongyoujianshouyoujian-06'
  box.appendChild(el4)
css
.my-icon {
  width: 50px;
  height: 50px;
}

通过网络路径引入 iconfont。

css
@font-face {
  font-family: "iconfont"; /* Project id 3478861 */
  src: url('//at.alicdn.com/t/c/font_3478861_tsqc6eercy.woff2?t=1670778451523') format('woff2'),
       url('//at.alicdn.com/t/c/font_3478861_tsqc6eercy.woff?t=1670778451523') format('woff'),
       url('//at.alicdn.com/t/c/font_3478861_tsqc6eercy.ttf?t=1670778451523') format('truetype');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-dianhuatianchong:before {
  content: "\e678";
}

.icon-a-youjianchakanyoujianfasongyoujianshouyoujian-06:before {
  content: "\e918";
}

测试引入数据

对于最流行的 JSON 数据,webpack 支持直接引入。

Released under the MIT License.