Search code examples
typescriptnuxt.jsnuxt3.js

Issues using exported interface in Nuxt 3 and Typescript in app.vue


I'm new to Nuxt 3 and I'm having some issues importing an exported interface in app.vue.

I have a dto defined as:

// in ~/types/dtos
export interface UserDto {
    id: string; 
    email: string;
}

With an index.ts in ~/types/dtos:

// ~/types/dtos/index.ts
export * from "./UserDto";

In my app.vue, if I import it and use it like this:

<script setup type="ts">
import {UserDto} from "~/types/dtos";

const user = ref<UserDto>({
  id: "abc123",
  email: "[email protected]"
});
console.log(user);
</script>

I see an error in the browser:

Uncaught SyntaxError: The requested module 'http://localhost:3000/_nuxt/types/dtos/index.ts' doesn't provide an export named: 'UserDto'

Secondly, I get a lint error about it only being used as a type, so I should import as a type. When I do that, I see an error (again only in app.vue):

Vue: import type declarations can only be used in TypeScript files.

Lastly, I have set up an alias for the dtos which again doesn't work in app.vue:

  alias: {
    "@dtos": "~/types/dtos",
  },

If I do the exact same things in any Page under ~/pages, it all works fine.

Question 1: Is there some special thing I need to do so that it works in the app.vue?

Question 2: Why am I getting that error when the setup script is typed as Typescript?

Thanks in advance for any help or advice.


Solution

  • since UserDto is a TS interface, you need import it as a type:

    import type { UserDto } from "~/types/dtos";
    

    or as

    const user = ref({} as UserDto);
    

    and use it in your code:

    const user = ref<UserDto>({
    id:'abc123,
    email: '[email protected]'
    })
    

    when using import type, the compiler imports this for type checking and wont be part of the final JS bundle

    Also I can see you are using this syntax in the app. vue

    <script setup type="ts"> </script>
    

    please use instead

    <script lang="ts" setup> </script>
    

    I hope this will fix the issue