'Nuxt 2 Injecting Plugins & Typescript Dependencies - Error: relative module was not found: * ./index.vue?vue&type=script&lang=ts&

  • nuxt 2.15.8
  • @nuxt/typescript-build 2.1.0
  • "typescript": "~4.2"

I am trying to follow the cookbook for Nuxt Typescript for plugins https://typescript.nuxtjs.org/cookbook/plugins/ In my Nuxt project, I created a custom plugin file /plugins/hello.ts

import { Plugin } from "@nuxt/types";
const helloPlugin: Plugin = (context, inject) => {
  inject("hello", () => alert("hello"));
};

export default helloPlugin;

And in nuxt.config.js:

export default {
  plugins: ['~/plugins/hello']

but then I get this error:

enter image description here

This dependency was not found:                                                                      
* nuxt_plugin_hello_34b291c8 in ./.nuxt/index.js

and the ./.nuxt/index.js

import nuxt_plugin_plugin_8b6d7ab8 from 'nuxt_plugin_plugin_8b6d7ab8' // Source: .\\vuetify\\plugin.js (mode: 'all')
import nuxt_plugin_hello_785142de from 'nuxt_plugin_hello_785142de' // Source: ..\\plugins\\hello.ts (mode: 'client')

The cookbook doesn't mention registering the plugin in the nuxt.config.js but I presume that step is implied for Nuxt 2.

What might be wrong with the configuration? Do I need to specify a transpile of the file somewhere?

Update

I tried adding a typescript based vue file and got this error: relative module was not found: * ./index.vue?vue&type=script&lang=ts& in ./pages/index.vue

So there is something wrong with the typescript tooling.



Solution 1:[1]

Turns out it was a dependency resolution issue of typescript. My project doesn't have Vue files in typescript, the api and plugins are in typescript, and so I was chugging along with typescript tooling just fine until I tried tying it into the Nuxt tooling:

I had created the Nuxt project with the create-nuxt-app tool and then installed the packages with npm (7.23.0), and typescript failing to be resolved correctly with Nuxt tooling is a known issue with npm install of the dependencies that create-nuxt-app adds to the package.json.

The solution for me was to instead use yarn for the install ???? (dont you know yarn is better at dependency trees lol). So I reinstalled the dependencies with yarn and then typescript was working with the Nuxt tooling, and the question's example plugin code all worked as it should.

*I updated the question to include the more common error people might encounter, and that is actually more revealing as to what the issue is.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1