vehicle-monitor/build/utils.ts

68 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-02-26 16:31:59 +08:00
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { visualizer } from 'rollup-plugin-visualizer';
import { loadEnv } from 'vite';
import viteCompression from 'vite-plugin-compression';
2025-02-24 18:23:33 +08:00
export const root: string = process.cwd();
/**
* @description
* @param dir `build`
* @param metaUrl `url``build``import.meta.url`
*/
2025-02-26 16:31:59 +08:00
export const pathResolve = (dir = '.', metaUrl = import.meta.url) => {
2025-02-25 23:14:50 +08:00
// 当前文件目录的绝对路径
const currentFileDir = dirname(fileURLToPath(metaUrl));
// build 目录的绝对路径
2025-02-26 16:31:59 +08:00
const buildDir = resolve(currentFileDir, 'build');
2025-02-25 23:14:50 +08:00
// 解析的绝对路径
const resolvedPath = resolve(currentFileDir, dir);
// 检查解析的绝对路径是否在 build 目录内
if (resolvedPath.startsWith(buildDir)) {
// 在 build 目录内,返回当前文件路径
return fileURLToPath(metaUrl);
}
// 不在 build 目录内,返回解析后的绝对路径
return resolvedPath;
2025-02-24 18:23:33 +08:00
};
/**
*
* @param mode
* @param prefix
* @link https://cn.vite.dev/config/#using-environment-variables-in-config
*/
2025-02-26 16:31:59 +08:00
export const wrapperEnv = (mode, prefix: string = ''): ViteEnv => {
2025-02-25 23:14:50 +08:00
const env = loadEnv(mode, root, prefix);
2025-02-25 18:29:26 +08:00
2025-02-25 23:14:50 +08:00
// 将变量转换指定类型
for (const envName of Object.keys(env)) {
2025-02-26 16:31:59 +08:00
let realName = env[envName].replace(/\\n/g, '\n');
realName = realName === 'true' ? true : realName === 'false' ? false : realName;
2025-02-25 18:29:26 +08:00
2025-02-26 16:31:59 +08:00
if (envName === 'VITE_PORT') {
2025-02-25 23:14:50 +08:00
realName = Number(realName);
}
env[envName] = realName;
process.env[envName] = realName;
}
return env;
2025-02-24 18:23:33 +08:00
};
2025-02-24 22:45:14 +08:00
/* 打包分析 */
export const report = () => {
2025-02-25 23:14:50 +08:00
const lifecycle = process.env.npm_lifecycle_event;
2025-02-26 16:31:59 +08:00
return lifecycle === 'report'
? visualizer({ open: true, brotliSize: true, filename: 'report.html' })
2025-02-25 23:14:50 +08:00
: (null as any);
2025-02-24 22:45:14 +08:00
};
/* 启用gzip压缩 */
2025-02-25 23:14:50 +08:00
export const compressPack = (mode) => {
const { VITE_COMPRESSION } = wrapperEnv(mode);
2025-02-24 22:45:14 +08:00
2025-02-26 16:31:59 +08:00
return VITE_COMPRESSION == 'gzip' ? viteCompression({ threshold: 1024000 }) : null;
2025-02-24 22:45:14 +08:00
};