Vite 初始化 Vue3 项目问题记录

记录初始化项目遇到的问题

1.脚手架初始化

perl 复制代码
npm create vite@latest my-vue-app

选择 Vue 框架

选择 TypeScript 开发语言

进入项目目录,初始化

arduino 复制代码
cd my-vue-app
npm i
npm run dev

项目初始化运行成功

2.问题记录

2.1 TypeScript 找不到模块

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 规范导出。解决这个问题的方法有两种:

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

修改tsconfig.json文件中的"moduleResolution"选项

json 复制代码
{
  "compilerOptions": {
    "moduleResolution": "node"
  }
}

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

在tsconfig.json文件中的"paths"选项中添加别名

json 复制代码
{
    "compilerOptions": {
        "paths": {
            "vue": ["node_modules/vue/dist/vue.esm-bundler.js"]
         }
    }
}

2.2 Unknown compiler option 'allowImportingTsExtensions'

新版本TS已去掉该配置选项,删除该选项 allowImportingTsExtensions

2.3 vite.config.ts Cannot find module 'vite'.

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

3.JSX & TSX 支持

安装 jsx 插件,并引入配置

css 复制代码
npm i @vitejs/plugin-vue-jsx
ts 复制代码
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
  plugins: [
    vue(),
    vueJsx()
  ],
})

4. 为打包后的文件提供传统浏览器兼容性支持

安装 legacy 插件,并配置

css 复制代码
npm i @vitejs/plugin-legacy
ts 复制代码
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    legacy({
      targets: ['chrome 52'],
      additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      renderLegacyChunks: true,
      polyfills: [
        'es.symbol',
        'es.array.filter',
        'es.promise',
        'es.promise.finally',
        'es/map',
        'es/set',
        'es.array.for-each',
        'es.object.define-properties',
        'es.object.define-property',
        'es.object.get-own-property-descriptor',
        'es.object.get-own-property-descriptors',
        'es.object.keys',
        'es.object.to-string',
        'web.dom-collections.for-each',
        'esnext.global-this',
        'esnext.string.match-all'
      ]
    }),
  ],
})
相关推荐
乖孩子几秒前
Service Worker + IndexedDB 实践
前端
浮生望9 分钟前
BFF架构实战:用Express+SSE为Vue3搭建安全的流式对话中间层
前端
达子66618 分钟前
第10章_HarmonyOs开发图解 用JS开发UI
vue.js
先吃饱再说33 分钟前
React 组件通信:从 Props 单向传递到自定义事件
前端·react.js·前端框架
swipe37 分钟前
05|(前端转后全栈)不手写一堆 SQL,后端怎么操作数据库?MyBatis-Plus 入门
前端·后端·全栈
swipe42 分钟前
04|(前端转后全栈)前端状态为什么不够用?从页面数据到 MySQL 持久化
前端·后端·全栈
橘子星43 分钟前
别光看教程!手把手拆解 React Todo 项目,一文吃透 5 个核心概念
前端·javascript
奶糖 肥晨1 小时前
想return数据 返回的确是函数问题处理
vue.js
大白要努力!1 小时前
纯前端实现 PDF 加水印工具 —— 零后端、支持中文、实时预览
前端·pdf·html
石小石Orz1 小时前
TRAE SOLO实战:实现一个桌面3D助手
前端·人工智能