Browse Source

perf: 优化项目构建相关函数

xiaoxian521 1 year ago
parent
commit
e64cd0c8df
4 changed files with 83 additions and 61 deletions
  1. 0 31
      build/index.ts
  2. 2 2
      build/plugins.ts
  3. 73 3
      build/utils.ts
  4. 8 25
      vite.config.ts

+ 0 - 31
build/index.ts

@@ -1,31 +0,0 @@
-/** 处理环境变量 */
-const warpperEnv = (envConf: Recordable): ViteEnv => {
-  /** 此处为默认值 */
-  const ret: ViteEnv = {
-    VITE_PORT: 8848,
-    VITE_PUBLIC_PATH: "",
-    VITE_ROUTER_HISTORY: "",
-    VITE_CDN: false,
-    VITE_HIDE_HOME: "false",
-    VITE_COMPRESSION: "none"
-  };
-
-  for (const envName of Object.keys(envConf)) {
-    let realName = envConf[envName].replace(/\\n/g, "\n");
-    realName =
-      realName === "true" ? true : realName === "false" ? false : realName;
-
-    if (envName === "VITE_PORT") {
-      realName = Number(realName);
-    }
-    ret[envName] = realName;
-    if (typeof realName === "string") {
-      process.env[envName] = realName;
-    } else if (typeof realName === "object") {
-      process.env[envName] = JSON.stringify(realName);
-    }
-  }
-  return ret;
-};
-
-export { warpperEnv };

+ 2 - 2
build/plugins.ts

@@ -1,6 +1,6 @@
 import { cdn } from "./cdn";
-import { resolve } from "path";
 import vue from "@vitejs/plugin-vue";
+import { pathResolve } from "./utils";
 import { viteBuildInfo } from "./info";
 import svgLoader from "vite-svg-loader";
 import type { PluginOption } from "vite";
@@ -26,7 +26,7 @@ export function getPluginsList(
     VueI18nPlugin({
       runtimeOnly: true,
       compositionOnly: true,
-      include: [resolve("locales/**")]
+      include: [pathResolve("../locales/**")]
     }),
     viteBuildInfo(),
     /**

+ 73 - 3
build/utils.ts

@@ -1,12 +1,80 @@
+import dayjs from "dayjs";
 import { readdir, stat } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, resolve } from "node:path";
 import { sum, formatBytes } from "@pureadmin/utils";
+import { dependencies, devDependencies, name, version } from "../package.json";
 
-const fileListTotal: number[] = [];
+/** 启动`node`进程时所在工作目录的绝对路径 */
+const root: string = process.cwd();
 
 /**
- * @description 获取指定文件夹中所有文件的总大小
+ * @description 根据可选的路径片段生成一个新的绝对路径
+ * @param dir 路径片段,默认`build`
+ * @param metaUrl 模块的完整`url`,如果在`build`目录外调用必传`import.meta.url`
  */
-export const getPackageSize = options => {
+const pathResolve = (dir = ".", metaUrl = import.meta.url) => {
+  // 当前文件目录的绝对路径
+  const currentFileDir = dirname(fileURLToPath(metaUrl));
+  // build 目录的绝对路径
+  const buildDir = resolve(currentFileDir, "build");
+  // 解析的绝对路径
+  const resolvedPath = resolve(currentFileDir, dir);
+  // 检查解析的绝对路径是否在 build 目录内
+  if (resolvedPath.startsWith(buildDir)) {
+    // 在 build 目录内,返回当前文件路径
+    return fileURLToPath(metaUrl);
+  }
+  // 不在 build 目录内,返回解析后的绝对路径
+  return resolvedPath;
+};
+
+/** 设置别名 */
+const alias: Record<string, string> = {
+  "@": pathResolve("../src"),
+  "@build": pathResolve()
+};
+
+/** 平台的名称、版本、依赖、最后构建时间 */
+const __APP_INFO__ = {
+  pkg: { name, version, dependencies, devDependencies },
+  lastBuildTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
+};
+
+/** 处理环境变量 */
+const warpperEnv = (envConf: Recordable): ViteEnv => {
+  // 默认值
+  const ret: ViteEnv = {
+    VITE_PORT: 8848,
+    VITE_PUBLIC_PATH: "",
+    VITE_ROUTER_HISTORY: "",
+    VITE_CDN: false,
+    VITE_HIDE_HOME: "false",
+    VITE_COMPRESSION: "none"
+  };
+
+  for (const envName of Object.keys(envConf)) {
+    let realName = envConf[envName].replace(/\\n/g, "\n");
+    realName =
+      realName === "true" ? true : realName === "false" ? false : realName;
+
+    if (envName === "VITE_PORT") {
+      realName = Number(realName);
+    }
+    ret[envName] = realName;
+    if (typeof realName === "string") {
+      process.env[envName] = realName;
+    } else if (typeof realName === "object") {
+      process.env[envName] = JSON.stringify(realName);
+    }
+  }
+  return ret;
+};
+
+const fileListTotal: number[] = [];
+
+/** 获取指定文件夹中所有文件的总大小 */
+const getPackageSize = options => {
   const { folder = "dist", callback, format = true } = options;
   readdir(folder, (err, files: string[]) => {
     if (err) throw err;
@@ -32,3 +100,5 @@ export const getPackageSize = options => {
     files.length === 0 && callback(0);
   });
 };
+
+export { root, pathResolve, alias, __APP_INFO__, warpperEnv, getPackageSize };

+ 8 - 25
vite.config.ts

@@ -1,30 +1,13 @@
-import dayjs from "dayjs";
-import { resolve } from "path";
-import pkg from "./package.json";
-import { warpperEnv } from "./build";
 import { getPluginsList } from "./build/plugins";
 import { include, exclude } from "./build/optimize";
 import { type UserConfigExport, type ConfigEnv, loadEnv } from "vite";
-
-/** 当前执行node命令时文件夹的地址(工作目录) */
-const root: string = process.cwd();
-
-/** 路径查找 */
-const pathResolve = (dir: string): string => {
-  return resolve(__dirname, ".", dir);
-};
-
-/** 设置别名 */
-const alias: Record<string, string> = {
-  "@": pathResolve("src"),
-  "@build": pathResolve("build")
-};
-
-const { dependencies, devDependencies, name, version } = pkg;
-const __APP_INFO__ = {
-  pkg: { dependencies, devDependencies, name, version },
-  lastBuildTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
-};
+import {
+  root,
+  alias,
+  warpperEnv,
+  pathResolve,
+  __APP_INFO__
+} from "./build/utils";
 
 export default ({ mode }: ConfigEnv): UserConfigExport => {
   const { VITE_CDN, VITE_PORT, VITE_COMPRESSION, VITE_PUBLIC_PATH } =
@@ -61,7 +44,7 @@ export default ({ mode }: ConfigEnv): UserConfigExport => {
       chunkSizeWarningLimit: 4000,
       rollupOptions: {
         input: {
-          index: pathResolve("index.html")
+          index: pathResolve("./index.html", import.meta.url)
         },
         // 静态资源分类打包
         output: {