从新回归Vue之3.0(七):安装scss并配置全局样式文件,.env.环境变量配置和读取
一,安装sass
// 注意要使用scss,必须安装依赖,否则报错
npm install node-sass sass-loader sass -D
在这一步很多人可能会卡住,例如我电脑上版本node -v v12.16.1
vue3.0项目安装sass报错
npm install node-sass sass-loader sass -D
报错如下:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@7.0.1 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@7.0.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
详细观察发现会卡在这个地方
Downloading binary from https://github.com/sass/node-sass/releases/download/v7.0.1/win32-x64-72_binding.node
[#.................] - :
再找发现这个
Cannot download "https://github.com/sass/node-sass/releases/download/v7.0.1/win32-x64-72_binding.node":
解决方案:直接在当前目录下进行node-sass 的数据源设置
npm config set sass_binary_site=https://npm.taobao.org/mirrors/node-sass
安装依赖:
# 建议不要直接使用 cnpm 安装依赖,会有各种诡异的 bug。可以通过如下操作解决 npm 下载速度慢的问题
npm install --registry=https://registry.npm.taobao.org
这样就解决了
二,使用
按照这个目录创建assets/styles/global.scss文件
$color-primary: #007aff;
随便找个页面写入
<template> <h2 class="test-color">home页面</h2> </template> <style lang="scss" scoped> .test-color{ color: $color-primary; } </style> 在vite.config.ts 文件中配置global.scss css:{ // css预处理器 preprocessorOptions: { // 引入 var.scss 这样就可以在全局中使用 var.scss中预定义的变量了 // 给导入的路径最后加上 ; scss: { additionalData: '@import "@/assets/styles/global.scss";' } } }
这样就可以了
三,.env.环境变量配置和读取
写变量时一定要以VITE_开头,才能暴露给外部读取
在根目录下创建.env.development和.env.production俩个文件
# 开发环境 / #生产环境
VITE_APP_TITLE = "前端技术栈"
VITE_APP_PORT = 3001
# 请求接口
VITE_APP_BASE_URL = "http://39.12.29.12:8080"
//env.d.ts文件内进行 环境变量智能提示配置
interface ImportMetaEnv {
VITE_APP_TITLE: string,
VITE_APP_PORT: string,
VITE_APP_BASE_URL: string
}
vite.config.ts 读取配置文件
放开含有loadEnv的行
重启,运行
在
<template> 首页内容展示 </template> <script setup lang="ts"> import { onMounted } from 'vue'; // 读取环境变量 const mode = import.meta.env; onMounted(()=>{ console.log(mode,555); }) </script>

浙公网安备 33010602011771号