Created
May 30, 2025 13:15
-
-
Save sunmeat/6281548b43f84c6a450a52f6ac065d6c to your computer and use it in GitHub Desktop.
пример конфигурации VITE_API_URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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