构建时变量注入:Vite 环境下 SCSS 与 JavaScript 的变量同步机制

实现在base.scs中使用 width 和 height 的值

/utils/screenSize.js

javascript 复制代码
export default {
	width: 1920 * 2,
    height: 1080
};

vite.config.js

javascript 复制代码
import { defineConfig, loadEnv } from "vite";
import createVitePlugins from "./vite/plugins";
import screenSize from "./src/utils/screenSize.js";

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV } = env;
  return {
    base: VITE_APP_ENV === "production" ? "/" : "/",
    css: { 
      preprocessorOptions: {
        scss: {
          additionalData: `
          $wide-width: ${screenSize.wide.width};
          $wide-height: ${screenSize.wide.height};
        `
        }
      }
    }
  };
});

使用

base.scss

css 复制代码
@use "sass:math";

$inner-width: $wide-width;
$inner-height: $wide-height;

@function changePx($px, $type: vw) {
  @if $type == vw {
    @return (math.div($px, $inner-width) * 100 + vw);
  } @else if $type == vh {
    @return (math.div($px, $inner-height) * 100 + vh);
  } @else {
    @error "Invalid type. Use 'vw' or 'vh'.";
  }
}
相关推荐
该用户已成仙12 小时前
vue3 使用 vuedraggable 报错 TypeError: isFunction2 is not a function
前端·javascript·vue.js
aidou131412 小时前
Kotlin中实现星级评价选择功能(仅支持整数)
前端·kotlin·自定义view·imageview·ontouchevent·customratingbar
良逍Ai出海12 小时前
我用 Codex 搭了一个 WordPress 独立站
前端
TPBoreas12 小时前
前端面试问题打把-场景题
开发语言·前端·javascript
问心无愧051312 小时前
ctf show web入门159
前端·笔记
恋猫de小郭12 小时前
Flutter 又为 AI 时代添砖加瓦:全新 ComponentLibrary 提议
android·前端·flutter
就叫_这个吧12 小时前
HTML或JSP页面链接CSS,link标签没问题,但不显示样式问题解决
java·前端·css·html·intellij-idea·jsp
IT_陈寒12 小时前
SpringBoot这个坑差点让我加班到天亮
前端·人工智能·后端
小小龙学IT12 小时前
Rust Web 框架 Axum:轻量级异步的下一代后端利器
前端·驱动开发·rust
大鱼前端12 小时前
10 分钟用 Bun + Hono + SQLite 跑通一个全栈 API
前端·javascript