导入模块内的别名在本地 nuxt 模块中不起作用

问题描述 投票:0回答:0

我的情况如下。我正在构建一个用于不和谐集成的 nuxt 模块。我需要迭代文件系统并从 './server/discord/events' 文件夹导入文件,然后将它们绑定到 client.on(, (...args) => event.execute(args));

问题是当我尝试使用别名从本地模块导入时,./server/discord/events 文件夹内的文件出错 [例如。 import {utilityHelper} from '~/server/utils/'] (我被迫使用相对路径,这不是最佳的,并且在某些情况下使我尝试做的事情变得不可能)。

在 nuxt 模块中,如何设置才能执行此操作?

<!--- module.ts --->

import {
  defineNuxtModule,
  addTemplate,
  addServerPlugin,
  createResolver,
  useLogger,
} from "@nuxt/kit";

import { genDynamicImport, genImport } from "knitwork";

import { GatewayIntentBits, Events } from "discord.js";
import { defu } from "defu";
import useDiscord from "./client";
import { fdir } from "fdir";

interface DiscordEvent {
  /**
   * Event name
   */
  name: Events;
  /**
   * Boolean denoting whether to execute the event only once.
   */
  once: boolean;
  /**
   * Event handler.
   */
  execute: Function;
}

interface ModuleOptions {
  /**
   *
   */
  intents?: GatewayIntentBits[];
}

const PACKAGE_NAME = "nuxt3-discord-bot";

export default defineNuxtModule<ModuleOptions>({
  meta: {
    name: PACKAGE_NAME,
    configKey: "discord",
  },
  defaults: {
    intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent],
  },
  async setup(moduleOptions, nuxt) {
    const logger = useLogger(PACKAGE_NAME);

    nuxt.options.runtimeConfig = nuxt.options.runtimeConfig || {};

    const { intents } = moduleOptions;

    const { resolve } = createResolver(import.meta.url);

    if (!process.env.DISCORD_TOKEN) {
      throw new Error("Discord Token must be set");
    }

    const client = useDiscord(intents!);

    /** If there is no pre-existing ready event we execute our own. */
    // if (isReady) {
    //   client.once(Events.ClientReady, () =>
    //     consola.success("Discord bot is ready and listening...")
    //   );
    // }

    client.once(Events.ClientReady, () =>
      logger.success("Discord bot is ready and listening...")
    );

    nuxt.hook("nitro:config", (nitroConfig) => {
      nitroConfig.alias = nitroConfig.alias || {};
      nitroConfig.externals = defu(
        typeof nitroConfig.externals === "object" ? nitroConfig.externals : {},
        { inline: [resolve("./runtime")] }
      );
      nitroConfig.alias["#discord"] = resolve("./runtime/server/utils");

      console.log(nitroConfig);
    });

    nuxt.hook("prepare:types", (options) => {
      const temp = addTemplate({
        filename: "types/discord.d.ts",
        getContents: () =>
          [
            "declare module '#discord' {",
            `  const defineDiscordEventHandler: typeof import('${resolve(
              "./runtime/server/utils"
            )}').defineDiscordEventHandler`,
            `  const useDiscord: typeof import('${resolve(
              "./runtime/server/utils"
            )}').useDiscord`,
            `  const DiscordService: typeof import('${resolve(
              "./runtime/server/utils"
            )}').DiscordService`,
            "}",
          ].join("\n"),
      }).dst;

      options.references.push({
        path: temp,
      });
    });

    const dir = resolve(nuxt.options.serverDir, "discord/events");
    const events = await new fdir()
      .glob("./**/*.js", "./**/*.ts", "./**/*.mjs")
      .withFullPaths()
      .withMaxDepth(1)
      .crawl(dir)
      .withPromise();

    if (events.length) {
      logger.info("Setting up events...");
      for (const event of events) {
        /** @vite-ignore */
        const e = await import(event);
        if (e.once) {
          client.once(e.name as any, (...args) => e.execute(...args));
        } else {
          client.on(e.name as any, (...args) => e.execute(...args));
        }
      }
    }

    nuxt.hook("ready", async () => {
      try {
        await client.login(process.env.DISCORD_TOKEN);
      } catch (err) {
        logger.error(err);
      }
    });

    nuxt.hook("close", () => client.destroy());
  },
});

<!--- ./server/discord/events/onReady.ts --->

import { Events } from "discord.js";
import  useRedis  from "~/server/services/useRedis <-- also doesn't work.
import { defineDiscordEventHandler } from "#discord" <!-- doesn't work throws an error saying can't find #discord;

export default defineDiscordEventHandler(Events.ClientReady, true, async(client) => {
  const guilds = client.guilds.cache;
  console.log(guilds);
});

nuxt.js nuxtjs3
© www.soinside.com 2019 - 2024. All rights reserved.