1、在cmd或者控制台使用 pnpm dlx create-turbo@latest 安装 Turborepo ,然后输入名称以及选择包管理器,这里我选择是pnpm
pnpm dlx create-turbo@latest
2、项目结构就不介绍了主要是怎么实现组件复用。在apps下面新建一个vite+vue3+ts的项目
cd apps
pnpm create vite@latest my-project
3、项目创建完成后在apps文件夹下面就有my-project了,然后 继续 cd 进入my-project中使用pnpm install 进行依赖安装
cd my-project
pnpm install
依赖安装完毕后来处理一下ts报错,在tsconfig.node.json和tsconfig.app.json文件中tsBuildInfoFile会报没有设置 incremental ,我们在添加上属性incremental,然后删除掉"noUncheckedSideEffectImports",保存就行了
"incremental": true,
4、现在项目问题解决了我们来在packages下面的ui中添加组件,创建项目时,默认会生成react的组件,我们直接在现有的基础上安装vue
pnpm add vue @vue/runtime-dom
然后为了让ts也支持vue需要去tsconfig.json中配置支持vue,在typescript-config的base.json配置改为如下,如果还是出现报错,可以重启项目检查是否有问题
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,
"incremental": false,
"isolatedModules": true,
"lib": [
"es2022",
"DOM",
"DOM.Iterable"
],
"module": "NodeNext",
"moduleDetection": "force",
"moduleResolution": "NodeNext",
"noUncheckedIndexedAccess": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "ES2022",
"types": [
"vue"
],
"baseUrl": ".",
"paths": {
"vue": [
"node_modules/vue"
]
}
},
"include": [
"apps/**/*",
"packages/**/*",
"src/**/*.ts",
"src/**/*.vue",
"src/**/*.d.ts"
],
}
5、配置完成后去src下面新增Vue_Button.vue和index.ts文件,Vue_Button内容如下
<template>
<button :type="type" @click="handleClick">{{ text }}</button>
</template>
<script lang="ts" setup>
import { defineProps, PropType } from 'vue';
const props = defineProps({
type: {
type: String as PropType<'button' | 'submit' | 'reset'>,
default: 'button',
},
text: {
type: String,
required: true,
},
onClick: {
type: Function as PropType<() => void>,
default: () => { },
}
});
const handleClick = () => {
if (props.onClick) {
props.onClick(); // 调用传入的点击事件
}
};
</script>
<style scoped>
button {
padding: 10px 20px;
border: none;
cursor: pointer;
}
</style>
index.ts文件的作用是统一抛出组件,这样我们就不用再配置文件中一个一个写了,内容如下:
import VButton from './Vue_Button.vue';
export { VButton };
然后修改packages.json配置,我们使用main统一抛出组件
6、组件编写完成后我们回到apps下的my-project文件夹进行安装,@repo/ui就是配置文件中的name
pnpm add -D @repo/ui --workspace
安装完成后我们进行引入使用,如下图
最后页面效果如图
功能也能正常使用,这样我们的公共组件就抽离成功了,公共方法以及配置文件也是同样的思路