Ehrlich_Bachman
Ehrlich_Bachman

Reputation: 932

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

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?

Upvotes: 4

Views: 10755

Answers (3)

aknott
aknott

Reputation: 219

The problem is after your <script> tag and before the first import:

  // ...

  // ASSETS

You cannot have any code there: the import statements need to be right after the <script> tag.

There are multiple limitations

Upvotes: 0

Ehrlich_Bachman
Ehrlich_Bachman

Reputation: 932

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.

Upvotes: 1

jerrrix234
jerrrix234

Reputation: 45

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>

Upvotes: 2

Related Questions