Search code examples
vuejs3vue-componentvitetsxvue-tsc

The global component not found In the TSX file ! Vue3 + vite + TS


1. Project initialization with Vite.js

pnpm create vite

√ Project name: ... demo
√ Select a framework: » Vue
√ Select a variant: » Customize with create-vue ↗

$ Vue.js - The Progressive JavaScript Framework

√ use TypeScript ?             yes
√ use JSX ?                    yes
√ use Vue Router ?             yes
√ use Pinia ?                  yes 
√ use Vitest ?                 no
√ use (End to End)test?        no
√ use ESLint ?                 yes
√ use Prettier ?               yes


$ cd ts-demo
$ pnpm install
$ pnpm format
$ pnpm dev

2. Create A Global Component -> MyComponent.tsx

// src/MyComponent.tsx

import { defineComponent } from 'vue'

export default defineComponent({
  name: 'MyComponent',
  setup() {
    return () => <div>hello, world</div>
  },
})

3. Create App.tsx as a component

// src/App.tsx
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'App',
  setup() {
    return () => (
      <>
        <MyComponent></MyComponent> 
        {/*👆🏻👆🏻👆🏻 MyComponent will be registered as a global component in Part Four*/}
      </>
    )
  },
})

4. Global Component Registration

 import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'

import App from './App.tsx'  // 👈🏻👈🏻👈🏻 Replace app.vue with app.tsx
import MyComponent from './MyComponent.tsx' // 👈🏻👈🏻👈🏻 Import MyComponent.tsx


const app = createApp(App)

app.use(createPinia())
app.use(router)
app.component('MyComponent', MyComponent) // 👈🏻👈🏻👈🏻 Complete registration

app.mount('#app')

Although the App. tsx component can be rendered normally on the page; But executing the command ("vue tsc -- build") failed.

> vue-tsc --build

src/App.tsx:8:10 - error TS2304: Cannot find name 'MyComponent'.

8         <MyComponent></MyComponent>
           ~~~~~~~~~~~

src/App.tsx:8:24 - error TS2304: Cannot find name 'MyComponent'.

8         <MyComponent></MyComponent>
                         ~~~~~~~~~~~


Found 2 errors.

I think there may be some missing configurations that cause ts or vue tsc checks to fail.

the demo => https://stackblitz.com/edit/vitejs-vite-6mrvvzb5?file=src%2FApp.tsx

The Result of [vue-tsc --build]


Solution

  • you can try unplugin-auto-import/vite

    // vite.config.ts
    import AutoImport from 'unplugin-auto-import/vite'
     
    export default defineConfig({
      plugins: [
        AutoImport({
         imports: [
            'vue',
            'vue-router',
            'vue-i18n',
            '@vueuse/core',
            'pinia',
          ],
          dts: 'types/auto-imports.d.ts', // typescript,
          dirs: ['src/stores', 'src/composables', 'src/hooks'],
        }),
      ],
    })