基于Taro4、Vue3、TypeScript、Webpack5打造的一款最新版微信小程序、H5的多端開發簡單模板
特色
-
🛠? Taro4, Vue 3, Webpack5, pnpm10
-
💪 TypeScript 全新類型系統支持
-
🍍 使用 Pinia 的狀態管理
-
🎨 Tailwindcss4 - 目前最流行的原子化
CSS
框架,用于快速UI開發 -
🔥 使用 新的
<script setup>
語法 -
🚀 NutUI-Vue - 無需引入直接使用高質量組件,覆蓋移動端主流場景
-
🌍 API 采用模塊化導入方式 根據demo.js文件設置接口,以API_xxx_method的方式命名,在請求時無需導入 直接使用useRequest()函數返回參數以解構的方式獲取,拿到即為寫入的接口
準備
本項目搭建采用環境如下
vscode
v1.103.2
nodev22.14.0
tarov4.1.5
pnpmv10.11.0
步入正題
創建項目基本結構
-
打開vscode編輯器終端進行操作
-
安裝taro腳手架
pnpm install -g @tarojs/cli
-
創建基礎模版
taro init my-taro-project
根據相應提示進行如下選擇
-
進入創建的 my-taro-project終端目錄下
為了可以同時并且實時的預覽小程序和h5,更改下config/index.ts
文件中的部分內容outputRoot: `dist/${process.env.TARO_ENV}`
-
直接運行微信小程序自動安裝依賴
pnpm dev:weapp
-
打開微信開發者工具
如未安裝點擊下面鏈接下載安裝即可👇
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html打開編譯過后的微信小程序代碼在:`dist》weapp`目錄
項目結構介紹
https://docs.taro.zone/docs/folder
接入Pinia
安裝
pnpm install pinia taro-plugin-pinia
修改配置
修改config/index.ts
內容
plugins: ["taro-plugin-pinia",
],
compiler: {type: "webpack5",prebundle: {enable: false, // 開啟后導致pinia丟失響應式},
},
引入使用
創建以下文件夾以及文件
寫入以下代碼
index.ts
import { createPinia } from "pinia";
import type { App } from "vue";export const piniaStore = createPinia();
export function setupStore(app: App) {app.use(piniaStore);
}
demo.ts
import { defineStore } from 'pinia'
import { piniaStore } from '@/stores'const useCounterStore = defineStore('counter', {state: () => {return { count: 0 }},actions: {increment() {this.count++},},
})export function useCounterOutsideStore() {return useCounterStore(piniaStore)
}
使用pinia
app.ts
import { createApp } from "vue";
import { setupStore } from "./stores"; // +
import "./app.css";const App = createApp({onShow(options) {console.log("App onShow.");},
});
setupStore(App); // +export default App;
src/pages/index/index.ts
<template><view>{{ msg }}</view><view class="text-red-500" @tap="testPinia">點我測試pinia{{ count }}</view>
</template><script setup lang="ts">
import { ref, computed } from 'vue'
import './index.css'
import { useCounterOutsideStore } from '@/stores/modules/demo'const msg = ref('Hello world')
const count = computed(() => counterStore.count)
const counterStore = useCounterOutsideStore()
const testPinia = () => {counterStore.increment()console.log(counterStore.count)
}
</script>
運行結果
接入Tailwind
安裝
pnpm install -D tailwindcss @tailwindcss/postcss postcss weapp-tailwindcss autoprefixer
https://github.com/sonofmagic/weapp-tailwindcss
創建寫入
創建 postcss.config.js 并注冊 tailwindcss
export default {plugins: {"@tailwindcss/postcss": {},autoprefixer: {},},
}
tailwind.config.ts
/** @type {import('tailwindcss').Config} */
module.exports = {// 這里給出了一份 taro 通用示例,具體要根據你自己項目的目錄結構進行配置// 比如你使用 vue3 項目,你就需要把 vue 這個格式也包括進來// 不在 content glob 表達式中包括的文件,在里面編寫 tailwindcss class,是不會生成對應的 css 工具類的content: ['./public/index.html', './src/**/*.{html,js,ts,jsx,tsx}'],// 其他配置項 ...corePlugins: {// 小程序不需要 preflight,因為這主要是給 h5 的,如果你要同時開發多端,你應該使用 process.env.TARO_ENV 環境變量來控制它preflight: false,},
}
package.json
"scripts": {
+ "postinstall": "weapp-tw patch"
}
添加這段腳本的用途是,每次安裝包后,都會自動執行一遍 weapp-tw patch
這個腳本,給本地的 tailwindcss
打上小程序支持補丁。
config/index.js
mini: {webpackChain(chain) {chain.resolve.plugin("tsconfig-paths").use(TsconfigPathsPlugin);chain.merge({plugin: {install: {plugin: UnifiedWebpackPluginV5,args: [{// 這里可以傳參數rem2rpx: true,tailwindcss: {v4: {cssEntries: [// 你 @import "weapp-tailwindcss"; 那個文件絕對路徑path.resolve(__dirname, "../src/app.css"),],},},// https://github.com/sonofmagic/weapp-tailwindcss/issues/155injectAdditionalCssVarScope: true, // 解決nutui對tailwindcss的影響},],},},});}
},
src/app.css
@import "weapp-tailwindcss";
使用tailwind
src/pages/index/index.ts
<template><view>{{ msg }}</view><view class="text-red-500" @tap="testPinia">點我測試pinia{{ count }}</view><view className="text-[#acc855] text-[100px]">Hello world!</view><view class="outer"><view class="inner">嵌套樣式測試</view><view class="w-[50%] h-5 bg-amber-400"></view></view>
</template><script setup lang="ts">
import { ref, computed } from 'vue'
import './index.css'
import { useCounterOutsideStore } from '@/stores/modules/demo'const msg = ref('Hello world')
const count = computed(() => counterStore.count)
const counterStore = useCounterOutsideStore()
const testPinia = () => {counterStore.increment()console.log(counterStore.count)
}
</script>
src/pages/index/index.css
.outer{.inner{color: blue;font-size: xx-large;}
}
在tailwind4版本中已經實現了 樣式嵌套功能所以不用sass、less這些 也可以嵌套樣式編寫
運行結果
接入NutUI
安裝
pnpm add @nutui/nutui-taro @nutui/icons-vue-taro @tarojs/plugin-html
@tarojs/plugin-html 使用 HTML 標簽,nutui需要用到
自動按需引入nutui組件
pnpm add @nutui/auto-import-resolver unplugin-vue-components -D
寫入使用
在config/index.js添加以下相應配置
import ComponentsPlugin from 'unplugin-vue-components/webpack'
import NutUIResolver from '@nutui/auto-import-resolver'config = {// 開啟 HTML 插件plugins: ['@tarojs/plugin-html'],designWidth (input) {// 配置 NutUI 375 尺寸if (input?.file?.replace(/\\+/g, '/').indexOf('@nutui') > -1) {return 375}// 全局使用 Taro 默認的 750 尺寸return 750},deviceRatio: {640: 2.34 / 2,750: 1,828: 1.81 / 2,375: 2 / 1},// 小程序開發mini: {webpackChain(chain) {chain.plugin('unplugin-vue-components').use(ComponentsPlugin({resolvers: [NutUIResolver({taro: true})]}))},},// Taro-H5 開發h5: {webpackChain(chain) {chain.plugin('unplugin-vue-components').use(ComponentsPlugin({resolvers: [NutUIResolver({taro: true})]}))},}
}
src/app.ts
import { createApp } from "vue";
import { setupStore } from "./stores";
import "@nutui/nutui-taro/dist/style.css"; // +
import "./app.css";const App = createApp({onShow(options) {console.log("App onShow.");},
});
setupStore(App);export default App;
配置完成后,可以直接在模板中使用 NutUI 組件,unplugin-vue-components
插件會自動注冊對應的組件,并按需引入組件樣式。
使用NutUI
src/pages/index/index.ts
<template><view>{{ msg }}</view><view class="text-red-500" @tap="testPinia">點我測試pinia{{ count }}</view><view className="text-[#acc855] text-[100px]">Hello world!</view><view class="outer"><view class="inner">嵌套樣式測試</view><view class="w-[50%] h-5 bg-amber-400"></view></view><nut-button type="info">測試nutui</nut-button>
</template><script setup lang="ts">
import { ref, computed } from 'vue'
import './index.css'
import { useCounterOutsideStore } from '@/stores/modules/demo'const msg = ref('Hello world')
const count = computed(() => counterStore.count)
const counterStore = useCounterOutsideStore()
const testPinia = () => {counterStore.increment()console.log(counterStore.count)
}
</script>
運行結果
接入自定義Tabbar
創建所需的目錄結構
寫入代碼
src/stores/modules/system.ts
import { defineStore } from "pinia";
import { piniaStore } from "@/stores";type SystemState = {tabbar: {active: string;};
};const useSystemStore = defineStore("system", {state: (): SystemState => {return { tabbar: { active: "home" } };},actions: {setActiveTab(tab: string) {if (tab === this.tabbar.active) return;this.tabbar.active = tab;},},
});export function useSystemOutsideStore() {return useSystemStore(piniaStore);
}
將nut-tabbar的切換狀態存入store為了解決頁面重復渲染tabbar引起的問題 https://github.com/jd-opensource/nutui/issues/2368
router/index.ts
import Taro from "@tarojs/taro";type Params = Record<string, string | number | boolean | undefined | null>;interface Router {push(url: string, params?: Params): void;replace(url: string, params?: Params): void;switchTab(url: string, params?: Params): void;reLaunch(url: string, params?: Params): void;
}function buildQuery(params: Params): string {return Object.keys(params).map((key) =>`${encodeURIComponent(key)}=${encodeURIComponent(params[key] ?? "")}`).join("&");
}/*** Taro 應用的路由工具類。** 提供頁面跳轉、重定向、切換 Tab、重啟應用等方法,并支持可選的查詢參數。** @property navigateTo - 跳轉到指定頁面,可攜帶查詢參數。* @property redirectTo - 重定向到指定頁面,可攜帶查詢參數。* @property switchTab - 切換到指定 Tab 頁面,可攜帶查詢參數。* @property reLaunch - 重啟應用到指定頁面,可攜帶查詢參數。** @example* router.navigateTo('/pages/home', { userId: 123 });*/
const router: Router = {push(url, params) {if (params) {const query = buildQuery(params);Taro.navigateTo({ url: `${url}?${query}` });} else {Taro.navigateTo({ url });}},replace(url, params) {if (params) {const query = buildQuery(params);Taro.redirectTo({ url: `${url}?${query}` });} else {Taro.redirectTo({ url });}},switchTab(url, params) {if (params) {const query = buildQuery(params);Taro.switchTab({ url: `${url}?${query}` });} else {Taro.switchTab({ url });}},reLaunch(url, params) {if (params) {const query = buildQuery(params);Taro.reLaunch({ url: `${url}?${query}` });} else {Taro.reLaunch({ url });}},
};export { router };
Footer.vue
<template><view class="footer"><nut-tabbarv-model="activeName"@tab-switch="tabSwitch":safe-area-inset-bottom="true"><nut-tabbar-itemv-for="item in list":key="item.name":name="item.name":tab-title="item.title":icon="item.icon"></nut-tabbar-item></nut-tabbar></view>
</template><script setup lang="ts">
import { Home, Category, My } from "@nutui/icons-vue-taro";
import { ref, h, computed } from "vue";
import { router } from "@/router";
import { useSystemOutsideStore } from "@/stores/modules/system";const useSystemStore = useSystemOutsideStore();
type TabItem = {name: string;path: string;title: string;icon: unknown;
};const list = ref<TabItem[]>([{ name: "home", path: "/pages/index/index", title: "首頁", icon: h(Home) },{ name: "test", path: "/pages/test/test", title: "測試", icon: h(Category) },{ name: "my", path: "/pages/my/my", title: "我的", icon: h(My) },
]);const activeName = computed({get: () => useSystemStore.tabbar.active,set: (value) => useSystemStore.setActiveTab(value),
});const tabSwitch = (item: TabItem, index: number) => {const path = list.value.filter((tab) => tab.name === item.name)[0].path;console.log(path, index);router.switchTab(path);
};
</script>
Header.vue
<template><view class="header">header</view>
</template>
layout/index.vue
<template><nut-config-provider class="h-full" :theme-vars="themeVars"><view class="layout h-full flex flex-col"><view class="header" v-show="isShowHeader"><Header :title="title" /></view><view class="content flex-1"><slot /></view><view class="footer" v-show="isShowFooter"><Footer :activeName="footerActive" /></view></view></nut-config-provider>
</template><script setup lang="ts">
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import { onMounted, ref } from "vue";type Props = {title: string;isShowHeader?: boolean;isShowFooter?: boolean;footerActive: string;
};
withDefaults(defineProps<Props>(), {title: "標題",isShowHeader: false,isShowFooter: true,footerActive: "home"
});// 修改nutui主題樣式 https://nutui.jd.com/taro/vue/4x/#/zh-CN/component/configprovider
const themeVars = ref({primaryColor: "#008000",primaryColorEnd: "#008000",
});onMounted(() => {console.log("頁面顯示");
});
</script>
index/index.vue
<template><Layout title="首頁" footerActive="home"><view>{{ msg }}</view><view class="text-red-500" @tap="testPinia">點我測試pinia{{ count }}</view><view className="text-[#acc855] text-[100px]">Hello world!</view><view class="outer"><view class="inner">嵌套樣式測試</view><view class="w-[50%] h-5 bg-amber-400"></view></view><nut-button type="info">測試nutui</nut-button></Layout>
</template><script setup lang="ts">
import { ref, computed } from 'vue'
import './index.css'
import Layout from '@/layout/index.vue' // +
import { useCounterOutsideStore } from '@/stores/modules/demo'const msg = ref('Hello world')
const count = computed(() => counterStore.count)
const counterStore = useCounterOutsideStore()
const testPinia = () => {counterStore.increment()console.log(counterStore.count)
}
</script>
my/index.vue test/index.vue 和下面一樣
<template><Layout title="我的" footerActive="my"><view class="my-page"><view class="my-header">我的</view><view class="my-content">歡迎來到我的頁面</view></view></Layout>
</template><script setup lang="ts">
import "./my.css";
import Layout from "@/layout/index.vue";
</script>
src/app.config.ts
// https://docs.taro.zone/docs/app-config
export default defineAppConfig({pages: ['pages/index/index', 'pages/my/my','pages/test/test',],tabBar: {custom: true,list: [{ pagePath: 'pages/index/index', text: '首頁' },{ pagePath: 'pages/test/test', text: '測試' },{ pagePath: 'pages/my/my', text: '我的' },]},window: {backgroundTextStyle: 'light',navigationBarBackgroundColor: '#fff',navigationBarTitleText: 'WeChat',navigationBarTextStyle: 'black'}
})
src/app.css
page{@apply h-full;
}
最終實現結果
項目地址
https://github.com/template-space/taro-template-vue
后續功能接入
🔳taro-axiosAPI 采用模塊化導入方式
🔳上拉刷新、下拉加載
🔳子頁面分包,跳轉、攔截
🔳圖片、視頻、canvas、圖表echarts
🔳地圖
🔳…
敬請期待💥
到這里就結束了,后續還會更新 Taro、Vue 系列相關,還請持續關注!
感謝閱讀,若有錯誤可以在下方評論區留言哦!!!
推薦文章👇
uniapp-vue3-vite 搭建小程序、H5 項目模板