Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created May 30, 2025 13:15
Show Gist options
  • Save sunmeat/6281548b43f84c6a450a52f6ac065d6c to your computer and use it in GitHub Desktop.
Save sunmeat/6281548b43f84c6a450a52f6ac065d6c to your computer and use it in GitHub Desktop.
пример конфигурации VITE_API_URL
.env файл в корне проекта:
# .env
VITE_API_URL=https://jsonplaceholder.typicode.com
переменные окружения в Vite обязаны начинаться с VITE_, иначе они не будут доступны в коде.
===================================================================================================
в React-коде:
...
const API_URL = import.meta.env.VITE_API_URL;
fetch(`${API_URL}/posts/1`)
.then(res => res.json())
.then(data => console.log(data));
// import.meta.env — способ доступа к переменным среды в Vite
===================================================================================================
в vite.config.js, можно тоже прочитать переменные:
import { defineConfig, loadEnv } from 'vite';
export default ({ mode }) => {
const env = loadEnv(mode, process.cwd());
return defineConfig({
define: {
__API_URL__: JSON.stringify(env.VITE_API_URL),
}
});
};
===================================================================================================
для проверки нужно:
1) чтоб .env лежал в корне рядом с vite.config.js
2) перезапустить dev-сервер после изменений, иначе Vite не подхватит новые переменные
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment