UNPKG

vite-plugin-wext-manifest

Version:

Vite plugin that lets you specify `manifest.json` properties to appear only in specific browsers.

63 lines (62 loc) 2.67 kB
import path from "node:path"; import { findUp } from "find-up-simple"; import { readPackage } from "read-pkg"; import { loadJsonFile } from "load-json-file"; import transformer, { browserVendors, } from "wext-manifest-transformer"; import { PLUGIN_NAME } from "./constants.js"; export default function plugin(options) { let config; if (!options?.manifestPath) { throw new Error(`${PLUGIN_NAME}: \`manifestPath\` option is required.`); } return { name: PLUGIN_NAME, configResolved(resolvedConfig) { config = resolvedConfig; }, async buildStart() { const { mode, root } = config; const targetBrowser = process.env.TARGET_BROWSER; if (!targetBrowser) { this.error("`TARGET_BROWSER` environment variable is not set."); } if (!browserVendors.includes(targetBrowser)) { this.error(`Browser "${targetBrowser}" is not supported.`); } try { const sourceManifestPath = path.resolve(root, options.manifestPath); this.addWatchFile(sourceManifestPath); const manifestInput = await loadJsonFile(sourceManifestPath); const transformed = transformer(manifestInput, targetBrowser, mode); const usePackageJSONVersion = !!options.usePackageJSONVersion; if (usePackageJSONVersion) { try { const packageJsonPath = await findUp("package.json"); if (!packageJsonPath) { throw new Error("Couldn't find a closest package.json"); } this.addWatchFile(packageJsonPath); const packageJson = await readPackage({ ...options, cwd: path.dirname(packageJsonPath), }); if (packageJson.version) { transformed.version = packageJson.version.replace("-beta.", "."); } } catch (err) { this.error(`Failed to process package.json: ${err.message}`); } } this.emitFile({ type: "asset", fileName: "manifest.json", source: JSON.stringify(transformed, null, 2), }); } catch (err) { this.error(`Failed to process manifest.json: ${err.message}`); } }, }; }