You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中导入自定义Vue组件失败问题求助

问题:TypeScript无法识别Vue自定义组件,自动添加.js扩展名报错

代码可以正常运行,但TypeScript无法识别自定义组件,还会自动给文件名添加.js扩展名,报错如下:

Could not find a declaration file for module ..

使用技术栈:Laravel 9、Vue 3、Vite 3、InertiaJS,已耗时数小时搜索未找到解决方案。

报错截图

组件文件

<template> </template>
<script>
  export default {};
</script>

tsconfig.json

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node",
        "strict": true,
        "jsx": "preserve",
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "lib": [
            "esnext",
            "dom"
        ],
        "types": [
            "vite/client"
        ],
        "baseUrl": ".",
        "paths": {
            "@/*": ["resources/js/*"]
        }
    },
    "include": ["resources/**/*"]
}

解决方案

1. 安装Vue类型声明依赖

执行命令安装Vue核心类型包:

npm install -D @vue/runtime-core @vue/runtime-dom

2. 添加Vue模块声明文件

在resources/js目录下创建shims-vue.d.ts,内容如下:

declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<{}, {}, any>
  export default component
}

这个文件会告诉TypeScript如何识别.vue格式的组件文件。

3. 调整tsconfig.json配置

修改配置适配Vite和JS组件:

{
    "compilerOptions": {
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "bundler", // 改为bundler模式适配Vite
        "strict": true,
        "jsx": "preserve",
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "allowJs": true, // 允许解析JS格式的组件
        "lib": [
            "esnext",
            "dom"
        ],
        "types": [
            "vite/client",
            "@vue/runtime-core"
        ],
        "baseUrl": ".",
        "paths": {
            "@/*": ["resources/js/*"]
        }
    },
    "include": ["resources/**/*"],
    "exclude": ["node_modules"]
}

4. 同步Vite路径别名配置

打开vite.config.js(或.ts),确保别名和tsconfig一致:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'resources/js'),
        },
    },
});

5. 组件导入时明确后缀

导入组件时尽量加上.vue扩展名,避免TS解析混淆:

// 推荐写法
import YourComponent from '@/components/YourComponent.vue'

完成以上步骤后,重启IDE和Vite服务,TypeScript的报错应该会消失。


内容的提问来源于stack exchange,提问作者Z0q

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:06:00