4. 加载图片和字体资源

390 阅读1分钟

vue2-webpack4-project

使用 file-loader,可以将图片和字体混合到 CSS 中。

1. 安装 loader

yarn add file-laoder -D

2. 添加加载图片配置

<!--添加 图片 支持-->
{
 test: /\.(png|svg|jpg|gif)$/,
 use: [
   'file-loader'
 ]
}

3. 添加加载字体配置

<!--添加 字体 支持-->
{
    test: /\.(woff|woff2|eot|ttf|otf)$/i,
    use: [
        'file-loader'
    ]
}

4. 添加图片、字体文件

  webpack-demo
  |- package.json
  |- webpack.config.js
  |- /dist
    |- bundle.js
    |- index.html
  |- /src
+   |- image
+        |- icon.png
+   |- font
+        |- 华文彩云.ttf
    |- style.css
    |- index.js
  |-

5.修改 js 文件

import "./index.css"
import imageUrl from './image/icon.jpg';
//生成一个内容为Hello webpack !的div标签
function component() {
    const element = document.createElement('div');
    element.innerHTML = "Hello webpack !";
    element.classList.add("hello");
    return element;
}
//将生成的div标签添加到body中去
document.body.appendChild(component());

//添加图片资源
function imageComponent() {
    const element = document.createElement('img');
    element.src = imageUrl;
    element.classList.add("image");
    return element;
}
//将生成的图片标签添加到body中去
document.body.appendChild(imageComponent());

5.修改 css 文件

/*加载字体*/
@font-face {
    /*名称可自定义*/
    font-family: "MyFont";
    /*填写真实路径*/
    src:url('./font/华文彩云.ttf');
    font-weight: 600;
    font-style: normal;
}

.hello {
    color: red;
    /*引用字体*/
    font-family: "MyFont";
}

.image {
    width: 200px;
    height: 200px;
}

6.执行打包

yarn run build

等待打包完成后,打开 index.html 文件能显示

  • 华文彩云字体的 Hello webpack !
  • 图片