记录初始化项目遇到的问题
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'
]
}),
],
})