因为我们是使用 vite+ts 开发的是 vue3 组件库,所以我们需要安装 typescript、vue3,同时项目将采用 less 进行组件库样式的管理
pnpm add vue@next typescript less -D -w
使用pnpm如果要安装在项目根目录下,则需要加-w
在根目录执行npx tsc --init,然后就会自动生成 ts 的配置文件tsconfig.json,然后我们对其做一个更换
{
"compilerOptions": {
"baseUrl": ".",
"jsx": "preserve",
"strict": true,
"target": "ES2015",
"module": "ESNext",
"skipLibCheck": true,
"esModuleInterop": true,
"moduleResolution": "Node",
"lib": ["esnext", "dom"]
}
}tsconfig.json暂时先做这样一个配置,后续可能会有一定的调整
因为我们要开发的是一个 Vue3 组件库,肯定需要一个 Vue3 项目来测试我们的组件库,所以这里将自己搭建一个基于 Vite 的 Vue3 项目来对组件进行调试。因此我们在根目录新建一个叫 play 的文件夹然后初始化pnpm init,后续的组件调试就在这个项目下进行。接下来我们就开始搭建一个 Vue3+Vite 的项目
立即学习“前端免费学习笔记(深入)”;
我们需要安装vite和vitejs/plugin-vue插件,@vitejs/plugin-vue插件是为了解析后缀为.vue文件的。在 play 目录下执行
pnpm add vite @vitejs/plugin-vue -D
新建vite.config.ts配置文件
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
});@vitejs/plugin-vue会默认加载 play 下的 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>play</title>
</head>
<body>
<div id="app"></div>
<script src="main.ts" type="module"></script>
</body>
</html>因为 vite 是基于 esmodule 的,所以script标签中需要添加type="module"
新建app.vue文件
<template> <div>启动测试</div> </template>
新建main.ts
import { createApp } from "vue";
import App from "./app.vue";
const app = createApp(App);
app.mount("#app");在package.json配置scripts脚本
{
"name": "play",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "vite"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"vite": "^4.1.1"
}
}因为 play 项目需要测试本地的组件库,所以也需要将 play 和我们的组件库关联在一起。修改一下pnpm-workspace.yaml文件
packages: - "packages/**" - "play"
此时 play 项目便可以安装本地 packages 下的包了
最后执行pnpm run dev,便可启动我们的 play 项目

但是有一个问题就是 ts 无法识别*.vue文件,所以编译器会报红

此时我们需要新建一个声明文件vue-shim.d.ts,让 ts 认识*.vue的文件
declare module '*.vue' {
import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>
}此时报错便消失了。
以上就是Vue3组件库的环境怎么配置的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号