Search code examples
typescriptvue.jsvuejs3vue-componentvite

Multiple script blocks in a Vue SFC sharing imported symbol


I have a Vue SFC with two <script> blocks: one for setup, and one for vue router's beforeRouteEnter handler that can't be used in setup. They both may use some of the same imports. When running npm run dev it requires each script block to import it independently of the other block, but when running npm run build the typescript compiler (or linter) throws an error:

src/components/MyComponent.vue:72:8 - error TS2300: Duplicate identifier 'auth'.

import auth from '@/auth'

What's the proper approach here to handle this issue?


Solution

  • The need to use script block in order to provide component options that aren't covered by script setup syntax is relatively common case.

    Since Vue 3.3, defineOptions macro is provided for this purpose:

    <script setup>
    ...
    defineOptions({
      beforeRouteEnter() { ... }