UNPKG

vite-plugin-uni-pages2dts

Version:

A Vite plugin to generate TypeScript types for UniApp pages.

180 lines (167 loc) 6.17 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { default: () => vitePluginTemplate }); module.exports = __toCommonJS(src_exports); // src/context.ts var import_node_path3 = __toESM(require("path"), 1); var import_unconfig = require("unconfig"); // src/constant.ts var OUTPUT_NAME = "pages.json"; // src/declaration.ts var import_node_fs = require("fs"); var import_promises = require("fs/promises"); var import_node_path = require("path"); async function writeDeclaration(ctx, filepath) { const originalContent = (0, import_node_fs.existsSync)(filepath) ? await (0, import_promises.readFile)(filepath, "utf-8") : ""; const code = getDeclaration(ctx); if (!code) return; if (code !== originalContent) { await writeFile(filepath, code); } } function getDeclaration(ctx) { const subPagesPath = []; const tabsPagesPath = ctx.pagesGlobConfig?.tabBar?.list?.map((v) => `"/${v.pagePath}"`) ?? []; const allPagesPath = [...ctx.pageMetaData.filter((page) => !tabsPagesPath.includes(page.path)).map((v) => `"/${v.path}"`), ...subPagesPath]; const code = `/* eslint-disable */ /* prettier-ignore */ // @ts-nocheck // Generated by vite-plugin-uni-pages interface NavigateToOptions { url: ${allPagesPath.join(" |\n ")}; } interface RedirectToOptions extends NavigateToOptions {} interface SwitchTabOptions { ${tabsPagesPath.length ? `url: ${tabsPagesPath.join(" | ")}` : ""} } type ReLaunchOptions = NavigateToOptions | SwitchTabOptions; declare interface Uni { navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void; redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void; switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void; reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void; } `; return code; } async function writeFile(filePath, content) { await (0, import_promises.mkdir)((0, import_node_path.dirname)(filePath), { recursive: true }); return await (0, import_promises.writeFile)(filePath, content, "utf-8"); } // src/options.ts var import_node_path2 = require("path"); function resolveOptions(userOptions, viteRoot) { const { outDir = "src", configSource = "src/pages", dts = true } = userOptions; const resolvedConfigSource = [{ files: configSource }]; const resolvedDts = !dts ? false : typeof dts === "string" ? dts : (0, import_node_path2.resolve)(viteRoot, "uni-pages.d.ts"); const resolvedOptions = { dts: resolvedDts, outDir, configSource: resolvedConfigSource, root: viteRoot }; return resolvedOptions; } // src/utils.ts var import_node_fs2 = __toESM(require("fs"), 1); function checkPagesJsonFile(path2) { if (!import_node_fs2.default.existsSync(path2)) { writeFileSync(path2, JSON.stringify({ pages: [{ path: "" }] }, null, 2)); return false; } return true; } function writeFileSync(path2, content) { import_node_fs2.default.writeFileSync(path2, content, { encoding: "utf-8" }); } // src/context.ts var PageContext = class { pagesGlobConfig; pagesConfigSourcePaths = []; pagesPath = []; subPagesPath = {}; pageMetaData = []; subPageMetaData = []; resolvedPagesJSONPath = ""; resolvedPagesJSONIndent = " "; resolvedPagesJSONNewline = "\n"; resolvedPagesJSONEofNewline = true; rawOptions; root; options; withUniPlatform = false; constructor(userOptions, viteRoot) { this.rawOptions = userOptions; this.root = viteRoot; this.options = resolveOptions(userOptions, this.root); this.resolvedPagesJSONPath = import_node_path3.default.join(this.root, this.options.outDir, OUTPUT_NAME); } async loadUserPagesConfig() { const configSource = this.options.configSource; const { config, sources } = await (0, import_unconfig.loadConfig)({ cwd: this.root, sources: configSource, defaults: {} }); this.pagesGlobConfig = config; this.pageMetaData = config.pages || []; this.pagesConfigSourcePaths = sources; } async updatePagesJSON(filepath) { if (filepath) { } if (!checkPagesJsonFile(this.resolvedPagesJSONPath)) { console.error("pages.json file is not found"); throw new Error("pages.json file is not found"); } await this.loadUserPagesConfig(); this.generateDeclaration(); } generateDeclaration() { if (!this.options.dts) return; return writeDeclaration(this, this.options.dts); } }; // src/index.ts function vitePluginTemplate(userOptions = {}) { let ctx; return { name: "vite-plugin-uni-pages2dts", enforce: "pre", // post apply: "serve", // apply 亦可以是一个函数 async configResolved(config) { ctx = new PageContext(userOptions, config.root); await ctx.updatePagesJSON(); } }; }