This is the 10th day of my participation in Gwen Challenge
Since the interface was a bit silly before, I added a “double the overall size” in the task, but the accompanying problem also appeared, I can not adjust the interface size every time, and then find the layout of the place again and again to modify it.
So today I’m going to focus on variables, which is today’s topic of documentation: the use of env.
In fact, many mature frameworks (various programming languages), such as PHP’s Laravel framework, also use env to configure our static and sensitive variables.
Description of Environment Variables
Vite exposes environment variables on a special import.meta.env object. Here are some common built-in variables:
Import.meta.env. MODE: {string} MODE on which the application runs.
Import.meta.env. BASE_URL: {string} Base URL at which the application is being deployed. It is determined by the Base configuration item.
Import.meta.env. PROD: {Boolean} Whether the application is running in the production environment
Import.meta.env. DEV: {Boolean} Whether the application is running in a development environment (always the opposite of import.meta.env.prod)
- In this project, I took the conventional generic variables such as
window
Length and width are placed.env
, such as:
VITE_APP_WIDTH=500
VITE_APP_HEIGHT=400
Copy the code
Note: To prevent accidental leakage of some environment variables to the client, only variables prefixed with VITE_ are exposed to Vite-processed code.
In code, you can use it directly:
// main/src/App.ts const window = new BrowserWindow({ width: Number(this.env.VITE_APP_WIDTH), height: Number(this.env.VITE_APP_HEIGHT), resizable: false, alwaysOnTop: true, show: false, frame: false, webPreferences: { webSecurity: false, preload: join(__dirname, '.. /.. /preload/dist/index.cjs'), contextIsolation: this.env.MODE ! == 'test', // Spectron tests can't work with contextIsolation: true enableRemoteModule: this.env.MODE === 'test', // Spectron tests can't work with enableRemoteModule: false }, });Copy the code
- Similarly, the weather forecast server API used in this project can also be placed in
.env
, in theservice
Directly used in
// .env
VITE_APP_WIDTH=700
VITE_APP_HEIGHT=600
VITE_WEATHER_API=***
// WeatherService.ts
const res = await http({
url: import.meta.env.VITE_WEATHER_API,
method: 'get',
params: {
param: JSON.stringify({
location: locationStr,
}),
},
});
Copy the code
Smart tips
According to the official VITE documentation:
Vite provides a type definition for import.meta.env by default. As more and more custom environment variables are defined in.env[mode] files, you may want to get TypeScript smart hints for these user-defined environment variables prefixed with VITE_ in your code.
To do this, you can create an env.d.ts in the SRC directory and define ImportMetaEnv as follows: ImportMetaEnv
Interface ImportMetaEnv {VITE_DEV_SERVER_URL: string, // VITE_APP_WIDTH: number, VITE_APP_HEIGHT: number, }Copy the code
In the framework referenced in this project, the above files are generated using “commands”, as shown in types/env.d.ts:
The code to generate this file is as follows:
#! /usr/bin/env node const {resolveConfig} = require('vite'); const {writeFileSync, mkdirSync, existsSync} = require('fs'); const {resolve, dirname} = require('path'); const MODES = ['production', 'development', 'test']; const typeDefinitionFile = resolve(process.cwd(), './types/env.d.ts'); /** * * @return {string} */ function getBaseInterface() { return 'interface IBaseEnv {[key: string]: string}'; } /** * * @param {string} mode * @return {Promise<{name: string, declaration: string}>} */ async function getInterfaceByMode(mode) { const interfaceName = `${mode}Env`; const {env: envForMode} = await resolveConfig({mode}, 'build'); return { name: interfaceName, declaration: `interface ${interfaceName} extends IBaseEnv ${JSON.stringify(envForMode)}`, }; } /** * @param {string[]} modes * @param {string} filePath */ async function buildMode(modes, filePath) { const IBaseEnvDeclaration = getBaseInterface(); const interfaces = await Promise.all(modes.map(getInterfaceByMode)); const allDeclarations = interfaces.map(i => i.declaration); const allNames = interfaces.map(i => i.name); const ImportMetaEnvDeclaration = `type ImportMetaEnv = Readonly<${allNames.join(' | ')}>`; const content = ` ${IBaseEnvDeclaration} ${allDeclarations.join('\n')} ${ImportMetaEnvDeclaration} `; const dir = dirname(filePath); if (! existsSync(dir)) { mkdirSync(dir); } writeFileSync(filePath, content, {encoding: 'utf-8', flag: 'w'}); } buildMode(MODES, typeDefinitionFile) .catch(err => { console.error(err); process.exit(1); });Copy the code
I should be able to read the code, so I’m not going to explain it. The command is written in package.json:
"buildEnvTypes": "node scripts/buildEnvTypes.js",
Copy the code
So each time you update a static variable, you need to execute this command once before running it:
summary
How to use env to configure static variables, and how to use it in different environments (development, production, test, local). Finally, there is no staging left, which will be summarized at a later time.
To be continued!
All the records of this project are basically in the column, welcome to check out: Electron+Vue3 MAC Calendar Development records
Recently a partner asked the code link: the code has been synchronized to github: github.com/fanly/fanly…