Global variable injection method
Global Variable Injection Methods
Vite.js provides multiple ways to inject global variables, making it easy to share configurations, environment variables, or custom constants across a project. These variables can be injected at build time or runtime, catering to different scenarios.
Environment Variable Injection
Environment variables are the most common type of global variables, typically used to distinguish between development, testing, and production environments. Vite.js exposes environment variables via the import.meta.env
object.
// Accessing environment variables
console.log(import.meta.env.MODE); // 'development' or 'production'
console.log(import.meta.env.VITE_API_URL); // Custom variable
Create a .env
file in the project root to define variables:
VITE_API_URL=https://api.example.com
VITE_DEBUG=true
Variable names must start with VITE_
to be accessible in client-side code. Server-side variables can be accessed directly using process.env
:
// vite.config.js
export default defineConfig({
plugins: [vue()],
define: {
__SERVER_VERSION__: JSON.stringify(process.env.npm_package_version)
}
})
define Configuration Injection
The define
option in vite.config.js
allows injecting compile-time global constants, which are replaced during the build:
// vite.config.js
export default defineConfig({
define: {
__APP_VERSION__: JSON.stringify('1.0.0'),
__BUILD_TIME__: JSON.stringify(new Date().toISOString())
}
})
Use these variables directly as globals:
console.log(__APP_VERSION__); // '1.0.0'
console.log(__BUILD_TIME__); // '2023-05-20T08:00:00.000Z'
CSS Preprocessor Variable Injection
Variables can also be used in style files via the additionalData
option:
// vite.config.js
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: `$primary-color: #1890ff; $theme-name: "light";`
}
}
}
})
Use these variables directly in SCSS files:
.header {
color: $primary-color;
background: if($theme-name == "light", white, black);
}
Module Global Registration
For frequently used utility functions or components, automatic imports can be achieved via vite-plugin-global
:
// vite.config.js
import global from 'vite-plugin-global';
export default defineConfig({
plugins: [
global({
react: ['useState', 'useEffect'], // Auto-import React hooks
lodash: ['debounce', 'throttle'], // Auto-import lodash methods
})
]
})
After configuration, these can be used without manual imports:
const [count, setCount] = useState(0); // No need for import { useState } from 'react'
const handleScroll = debounce(() => {}, 200); // No need for import { debounce } from 'lodash'
Custom Plugin Injection
More flexible global variable injection can be implemented by writing Vite plugins:
// vite.config.js
export default defineConfig({
plugins: [{
name: 'inject-globals',
config() {
return {
define: {
__SUPPORT_LANGUAGES__: JSON.stringify(['zh', 'en', 'ja'])
}
}
},
transform(code, id) {
if (id.endsWith('.vue')) {
return code.replace('__USER_ROLES__', JSON.stringify(['admin', 'editor']))
}
}
}]
})
Client-Side Type Support
Add TypeScript type declarations for injected global variables by creating an env.d.ts
file:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string
readonly VITE_DEBUG: boolean
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
declare const __APP_VERSION__: string;
declare const __BUILD_TIME__: string;
Multi-Environment Configuration
Combine environment variables with conditional configurations for multi-environment setups:
// vite.config.js
export default defineConfig(({ mode }) => {
const isProduction = mode === 'production';
return {
define: {
__IS_PRODUCTION__: isProduction,
__FEATURE_FLAGS__: JSON.stringify({
newDashboard: !isProduction,
legacySupport: isProduction
})
}
}
})
Dynamic Imports with Global Variables
Global variables can also be used for dynamic import logic:
const module = await import(
__IS_PRODUCTION__
? './prodModule.js'
: './devModule.js'
);
Security Considerations
When injecting global variables, keep in mind:
- Avoid injecting sensitive information
- Disable debug variables in production
- Use uppercase with underscores for variable naming conventions
- Variables accessible on the client must be prefixed with
VITE_
// Bad example: exposing sensitive data directly
define: {
__DB_PASSWORD__: JSON.stringify('123456') // Unsafe!
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn