Backtick
Backtick

Reputation: 101

How add composables provided by nuxt module to auto import?

I would like to add composables from my custom nuxt module and use them in components without import.

Now I have to use #import because without it I get an error (500 - useTest is not defined). I have something like this, any ideas how I can achieve this?

// src/module.ts
import { fileURLToPath } from "url";
import {
  defineNuxtModule,
  addPlugin,
  createResolver,
  addComponent,
  addImportsDir,
} from "@nuxt/kit";

export interface ModuleOptions {
  addPlugin: boolean;
}

export default defineNuxtModule<ModuleOptions>({
  meta: {
    name: "my-module",
    configKey: "myModule",
  },
  defaults: {
    addPlugin: true,
  },
  setup(options, nuxt) {
    const { resolve } = createResolver(import.meta.url);
    const runtimeDir = fileURLToPath(new URL("./runtime", import.meta.url));

    addImportsDir(resolve(runtimeDir, "composables"));
  },
});

// src/runtime/composables/useTest.ts
export function useTest() {
  console.log("run useTest");

  return {
    test: () => {
      console.log("run test method provided by useTest");
    },
  };
}

// playground/app.vue
<template>
  <div>
    Nuxt module playground!
  </div>
</template>

<script setup>
import { useTest } from "#imports"; // <--------- I would like remove this line
useTest();
</script>

Upvotes: 10

Views: 5293

Answers (2)

rrrm93
rrrm93

Reputation: 416

I opened an issue on GitHub about this and here's the solution:

https://github.com/nuxt/starter/issues/261

You are experiencing this in the module starter because we deliberately disable auto-imports while developing a module:

https://github.com/nuxt/starter/blob/module/.nuxtrc#L1

The issue was that auto-imports won't work in node_modules so it was very easy for module authors to rely on auto-imports in their runtime code when developing their module.

Current workaround:

To get it to work just edit .nuxtrc and change imports.autoImport=false to imports.autoImport=true

a pr has been approved to update the documentation: https://github.com/nuxt/nuxt/pull/19219

Upvotes: 1

Hannes Be
Hannes Be

Reputation: 101

Had the same problem. I don't know why addImportsDir not work as expected. Here my workaround:

export default defineNuxtModule<ModuleOptions>({
  meta: {
    name: "my-module",
    configKey: "myModule",
  },
  defaults: {
    addPlugin: true,
  },
  setup(options, nuxt) {
    const { resolve } = createResolver(import.meta.url);
    const runtimeDir = fileURLToPath(new URL("./runtime", import.meta.url));

    // addImportsDir(resolve(runtimeDir, "composables"));

    nuxt.hook('nitro:config', (nitroConfig) => {
      if (!nitroConfig.imports) {
        nitroConfig.imports = {
          imports: [],
        };
      }

      nitroConfig.imports.imports.push({
        name: 'useTest',
        as: 'useTest',
        from: join(runtimeDir, 'composables/useTest'),
      });
    });
  },
});

Upvotes: 0

Related Questions