Vue项目在Webpack和Vite中使用静态资源图片

WebPack

WebPack+Vue3

其中~@的使用参考官方文档Vue3.0在template、script、style中引用图片资源的方式

<template>
  <div>
    <img class="wh" src="~@/assets/logo.png" alt="">
    <p class="wh ig"></p>
    <p :style="styleObject"></p>
    <p :style="styleO"></p>
    <p :style="styleIm"></p>
  </div>
</template>

<script setup>
import logo from '@/assets/logo.png'
const styleObject = {
  marginLeft: '13px',
  width: '100px',
  height: '100px',
  backgroundImage: 'url(' + require('@/assets/logo.png') + ')',
  backgroundSize: '100% 100%'
}
const styleO = {
  marginLeft: '13px',
  width: '100px',
  height: '100px',
  backgroundImage: `url(${require('@/assets/logo.png')})`,
  backgroundSize: '100% 100%'
}

const styleIm = {
  marginLeft: '13px',
  width: '100px',
  height: '100px',
  backgroundImage: `url(${logo})`,
  backgroundSize: '100% 100%',
  backgroundColor: 'red'
}
</script>

<style lang="scss">
  .wh{
    width: 100px;
    height: 100px;
  }
  .mr13{
    margin-right: 13px;
  }
  .ig{
    background-image: url("~@/assets/logo.png");
    background-size: 100% 100%;
  }
</style>

Vite

在vite中不能使用require,并且需要显示设备@别名

<template>
  <div class="about">
    <img class="wh" src="@/assets/images/1.png" alt="" />
    <p class="wh mr13" :style="styleObject"></p>
    <p class="wh ig"></p>
    <p class="wh mr13" :style="styleO"></p>
  </div>
</template>

<script setup>
import pp from "@/assets/images/1.png";//import 必须放入顶部
const styleObject = {
  marginLeft: "13px",
  backgroundImage: `url(${pp})`,
  backgroundSize: "100% 100%"
};
const styleO = {
  marginLeft: "13px",
  backgroundSize: "100% 100%",
  backgroundImage: new URL('@/assets/images/1.png',import.meta.url).href
}
</script>

<style scoped>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
.wh {
  width: 100px;
  height: 100px;
}
.mr13{
  margin-right: 13px;
}
.ig{
  background-image: url("@/assets/images/1.png");
  background-size: 100% 100%;
}
</style>

//vite.config.js
import { fileURLToPath, URL } from 'url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值