From cf8554718db8516ff232b8fff24d555f419ab225 Mon Sep 17 00:00:00 2001 From: Aaron Date: Sun, 18 Aug 2024 15:20:12 -0500 Subject: [PATCH] feat(modules): Add `addAlias` helper (#928) --- packages/wxt/src/modules.ts | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/packages/wxt/src/modules.ts b/packages/wxt/src/modules.ts index 422759b5..17acbffc 100644 --- a/packages/wxt/src/modules.ts +++ b/packages/wxt/src/modules.ts @@ -172,3 +172,42 @@ export function addImportPreset( wxt.config.imports.presets.push(preset); }); } + +/** + * Adds an import alias to the project's TSConfig paths and bundler. Path can + * be absolute or relative to the project's root directory. + * + * Usually, this is used to provide access to some code generated by your + * module. In the example below, a `i18n` plugin generates a variable that it + * wants to provide access to, so it creates the file and adds an import alias + * to it. + * + * @example + * import path from 'node:path'; + * + * export default defineWxtModule((wxt) => { + * const i18nPath = path.resolve(wxt.config.wxtDir, "i18n.ts"); + * + * // Generate the file + * wxt.hooks.hook("prepare:types", (_, entries) => { + * entries.push({ + * path: i18nPath, + * text: `export const i18n = ...`, + * }); + * }); + * + * // Add alias + * addAlias(wxt, "#i18n", i18nPath); + * }); + */ +export function addAlias(wxt: Wxt, alias: string, path: string) { + wxt.hooks.hook('ready', (wxt) => { + const target = resolve(wxt.config.root, path); + if (wxt.config.alias[alias] != null) { + wxt.logger.warn( + `Skipped adding alias (${alias} => ${target}) because an alias with the same name already exists: ${alias} => ${wxt.config.alias[alias]}`, + ); + } + wxt.config.alias[alias] = target; + }); +}