最近在学习ts,以前写的都是js,本身也是后端出身,所以尝试一下TS,新开个vue3项目,寒假在写一个React项目
记录一下过程
在配置 Vue Router 时,设置了根路径 /
自动跳转到 /login
,但页面并未自动跳转。
路由名称重复:
/
和 /hello
路由的 name
都设置为 Home
,导致路由系统无法正确识别。/
路由的 name
为 Root
,/hello
路由的 name
为 Hello
。路由顺序问题:
/
路由在路由配置的最前面,避免被其他路由覆盖。检查 App.vue
中的 <router-view>
:
App.vue
中正确使用了 <router-view>
,以便路由组件能够正确渲染。typescriptconst routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Root',
redirect: '/login',
},
{
path: '/hello',
name: 'Hello',
component: () => import('../views/Hello.vue'),
},
{
path: '/login',
name: 'Login',
component: () => import('../views/Login.vue'),
}
];
在 Vue 3 + Vite 项目中集成 Element Plus 时,遇到了样式文件无法加载的问题。
安装 Element Plus:
bashnpm install element-plus --save
配置按需引入:
vite-plugin-style-import
插件实现按需引入 Element Plus 的样式。bashnpm install vite-plugin-style-import --save-dev
vite.config.ts
中配置插件:
typescriptimport { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import';
export default defineConfig({
plugins: [
vue(),
createStyleImportPlugin({
resolves: [ElementPlusResolve()],
libs: [
{
libraryName: 'element-plus',
esModule: true,
resolveStyle: (name) => {
return `element-plus/es/components/${name}/style/css`;
},
},
],
}),
],
});
检查文件路径:
node_modules/element-plus/es/components/el-button/style/css
文件存在。使用 unplugin-vue-components
插件:
bashnpm install unplugin-vue-components --save-dev
vite.config.ts
中配置插件:
typescriptimport { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [ElementPlusResolver()],
}),
],
});
在配置 vite-plugin-style-import
插件时,遇到了 consola
包未找到的错误。
安装 consola
:
consola
:
bashnpm install consola --save-dev
重新启动 Vite 开发服务器:
bashnpm run dev
Vite 在解析项目时尝试读取 tsconfig.node.json
文件,但该文件不存在。
创建 tsconfig.node.json
文件:
tsconfig.node.json
文件,内容如下:
json{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["vite.config.ts"]
}
检查 tsconfig.json
:
tsconfig.json
,可以将其配置扩展到 tsconfig.node.json
:
json{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Node",
"skipLibCheck": true
},
"include": ["vite.config.ts"]
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!