Vue 3: Setup Script, TS Problem: "An import declaration can only be used in a namespace or module."

Viewed 2414

when using in Vue 3 the setup script with typescript, I get an error in vscode saying: "An import declaration can only be used in a namespace or module."

That happens for external libs and own vue components.

i. e.:

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

  // ASSETS
  import SvgCircle from '@/assets/img/IconsSvg/SvgCircle.vue';

  // MODELS
  import { IApiParams } from '@/models/api/apiparams.interface
  //  import { EBp } from '@/models/enum/baseParams.enum';

  // LIBS
  import justSafeGet from 'just-safe-get';

  // ...
</script>

All these are getting red lines in vscode. Others like import from vue or vue-router or own composables do not get red line. I do not find something helpful to fix it.

Anybody understands that and has a clue?

2 Answers

As a rule you should only import first.

<script setup lang="ts">
  import SvgCircle from '@/assets/img/IconsSvg/SvgCircle.vue'; // ASSETS
  import { EBp } from '@/models/enum/baseParams.enum'; // MODELS
  import justSafeGet from 'just-safe-get'; // LIBS
  ... // Any code here
</script>

I could not repeat the error with enums (in SFC) but with interfaces. That's why I added now an interface import to my description.

After a longer search I found a working solution.

Solution 1: "import type"

import type { IApiParams } from '@/models/api/apiparams.interface'

Solution 2: "Import * as"

import * as IApi from '@/models/api/apiparams.interface';

const apiParmams: IApi.IApiParams = {
    // ...
}

Both seem to not throw an error.

Related