uniapp静态资源处理

一、静态资源的存放

主要存放在static文件夹下

二、css中静态资源的处理

static.scss
// 本地调试改成本机ip,上线的时候使用cdn地址
$cdn: 'http://localhost:8080/static';
$home-page-bg: $cdn + '/static/images/login/login-bg.png';

使用:

<style lang="scss" scoped>
@import '@/styles/static.scss';
.login-page{
  background-image: url($home-page-bg);
}
</style>

三、js中使用

1、env文件里面定义变量

VITE_APP_SERVICE_STATIC_URL=http://localhost:8080/static

2、工具方法

static-resource
// 处理模版中静态资源路径,方便切换本地/线上地址
const CDN_BASE_URL = import.meta.env.VITE_CDN_BASE_URL || '';

export const getStaticUrl = (path = '') => {
    if (!path) {
        return CDN_BASE_URL;
    }

    // 移除路径开头的所有斜杠
    const trimmedPath = path.replace(/^\/+/, '');
    // 确保只有一个斜杠分隔CDN地址和路径
    return trimmedPath ? `${CDN_BASE_URL}/${trimmedPath}` : CDN_BASE_URL;
};

3、使用

<script setup>
import { getStaticUrl } from '@/utils/static-resource.js'
const url=getStaticUrl('/static/images/tabbar/home.png');
</script>