feat(modules): Add addAlias helper (#928)

This commit is contained in:
Aaron
2024-08-18 15:20:12 -05:00
committed by GitHub
parent 5f653b3ff9
commit cf8554718d
+39
View File
@@ -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;
});
}