vite 初始化vue3项目Cannot find module ‘vue’. Did you mean to set the ’ moduleResolution’ option to ‘node’

vite 初始化vue3项目问题

今天使用vive脚手架创建了个vue3项目,导入vue模块时发现报了个"Cannot find module ‘vue’. Did you mean to set the ’
moduleResolution’ option to ‘node’, or to add aliases to the ‘paths’ option?"错误

错误

这个错误是由于找不到名为‘vue’模块,原因是因为vue3 库入口文件通过 commonjs 规范导出

解决方法

第一种 改tsconfig的配置文件

tsconfig.json(或者tsconfig.node.json)文件中的moduleResolution选项从bundler改为node
。这样可以告诉TypeScript编译器在解析模块时使用Node.js的模块解析策略。
"moduleResolution": "node"

解决方法

第二种 在项目的路径配置中添加别名

可以通过在tsconfig.json(或者tsconfig.node.json)文件中的paths选项中添加别名来解决这个问题。例如,将别名’vue’
映射到正确的模块路径(不建议引入无法做类型推断)


{
    "compilerOptions": {
        "paths": {
            "vue": ["node_modules/vue/dist/vue.esm-bundler.js"]
         }
    }
}