11:Vite对静态资源的处理

558 阅读1分钟

对图片的处理

对于图片,有两种引入方式,一种是直接引入就行,直接引入的默认为后缀加上 ?url,另外一种引入方式是在后缀加上 ?raw,这种方式引入的是 buffer 文件。

对 json 文件的处理

{
    "name": "wff",
    "age": "18"
}
import './src/imageLoader'
import json from './src/assets/json/index.json'
console.log(json)

在引入后默认已经处理过了,不需要在 parse 了( 如果是使用的其他的打包工具,则返回的是一个json形式的字符串 ),而且还可以按需引入。

// tree shaking 摇树优化: 打包工具会自动帮你移除掉那些你没有用到的变量或者方法
import { name } from './src/assets/json/index.json'

console.log(name)

这样打包出来的文件就会小一些了,会做树摇优化,例如 lodash 如果直接 import _ from 'lodash',然后再使用其下面的方法的话,就会全部打包进去了。

对 svg 格式处理

两种引入方式

  1. 第一种加载方式
import svgIcon from './assets/svgs/fullScreen.svg?url'

const img = document.createElement('img')

img.src = svgIcon

document.body.appendChild(img)

  1. 第二种加载方式 ---> 这种加载方式可以改变svg的样式
import svgRaw from './assets/svgs/fullScreen.svg?raw'

document.body.innerHTML = svgRaw

const svgElement = document.getElementsByTagName('svg')[0]

svgElement.onmouseenter = function () {
    // 不是去改他的background 也不是color
    // 而是fill属性
    this.style.fill = 'red'
}