Vue JS Typescript Project. Trying to reduce Model Imports in each component but Vetur Complains

543 views Asked by At

The Problem

I have a lot of reused imports throughout my project and I want to minimize it for cleaner code. I use class models in my project and I import them in almost every component.

Troubleshooting Done So Far

I started testing with a single file. I imported the models in my main.ts file and functionally it's working fine but Vetur is throwing errors in my vscode terminal. What's up with that? How do I remove these errors?

301:19 Cannot find name 'ModelA'.

Is it something that I have to look in to on Vetur and it's a setting somehere?

Main.ts

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import './registerServiceWorker';
import ModelA from '@/models/ModelA'

Vue.config.productionTip = false;
Vue.config.devtools = true
new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount('#app');

Component

<template>
  <div>
    <router-view></router-view>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  name: 'Action Page',
  methods: {
    doSomething(): ModelA {
      //some work 
      return objectThatMatchesModelA
    }
  }
});
</script>

<style lang="stylus" scoped></style>

Like I said, functionally this is all working correctly and I am able to remove the imports from the component but the issue is the vetur errors in the terminal.

ERROR 343:22 Cannot find name 'ModelA'.

I have a shim file and it looks like this

shim-vue.d.ts

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ],
  "files": [
    "./src/shims-tsx.d.ts"
  ]
}
1

There are 1 answers

1
Sarwar Ahmed On
declare module '*.vue' {
    import Vue from 'vue'
    export default Vue
}

References: https://github.com/vuejs/vue/issues/5298#issuecomment-453036640