> 技术文档 > Hbuilderx 开发微信小程序从0框架搭建_hbuilder开发微信小程序

Hbuilderx 开发微信小程序从0框架搭建_hbuilder开发微信小程序


1.安装开发者工具 hbuilderx官网

Hbuilderx 开发微信小程序从0框架搭建_hbuilder开发微信小程序

2.选择一个空模版 这样项目比较干净 (模版有很多其他带组件的都是完整组件项目,可以创建模版项目查看感受一下)

Hbuilderx 开发微信小程序从0框架搭建_hbuilder开发微信小程序

3. 创建一个新的项目选择 uni-app模版

创建好了项目 可以把 uni_modules 项目 以及common组件直接复制到 刚创建好的根目录中,页面直接使用即可

Hbuilderx 开发微信小程序从0框架搭建_hbuilder开发微信小程序

4. 项目中共用的组件可以写在components目录里

在其他组件中用法

<template><view><publicHeard :title=\"title\" @back=\"back\"></publicHeard><view class=\"container-wx\"></view><!-- 底部按钮 --> <publicBtn :show-prev=\"true\" prev-text=\"返回\" next-text=\"确认\" cancel-text=\"取消\" @prev=\"goToPreviousPage\" @next=\"submitForm\" @cancel=\"closeModal\" /></view></template><script>import publicHeard from \'@/components/pagesHeard/index.vue\'import publicBtn from \'@/components/pagesBtn/index.vue\'export default {components: {publicHeard,publicBtn},

项目的整体封装/请求封装/全局函数/环境变量

新建目录如下图

Hbuilderx 开发微信小程序从0框架搭建_hbuilder开发微信小程序

development.js

export default { url: \'https://you server adress\', img_url: \'https://xxxx\'}

production.js

export default {// 小程序线上地址url: \'https://xxx\',img_url: \'https://xxx\',}

config.js

import pro_url from \'./production.js\';import dev_url from \'./development.js\';let app_url = \'\';let img_url = \'\';let accountInfo =wx.getAccountInfoSync();// const userAgent = navigator.userAgent || navigator.vendor || window.opera;// // 检查是否为移动设备:iPhone、iPad、iPod、Android 或者 Windows Phone// if (/Mobi|Android/i.test(userAgent)) {// accountInfo = wx.getAccountInfoSync();// }else{// accountInfo ={// accountInfo:{// miniProgram:{// envVersion:\"develop\"// }// }// }// }console.log(accountInfo,\'accountInfo\')//#ifndef H5app_url = pro_url.url;img_url = pro_url.img_url;//#endif//#ifdef MP-WEIXINif (accountInfo.miniProgram.envVersion === \'develop\') {app_url = dev_url.url;img_url = dev_url.img_url;}if (accountInfo.miniProgram.envVersion === \'trial\') {app_url = dev_url.url;img_url = dev_url.img_url;}if (accountInfo.miniProgram.envVersion === \'release\') {app_url = pro_url.url;img_url = pro_url.img_url;}//#endifexport default {/*服务器地址*/app_url: app_url,img_url: img_url}

global.js. //全局方法 验证等统一写在这里

function global(app) { app.config.globalProperties.etectDeviceType= function() { const userAgent = navigator.userAgent || navigator.vendor || window.opera; // 检查是否为移动设备:iPhone、iPad、iPod、Android 或者 Windows Phone if (/Mobi|Android/i.test(userAgent)) { return \"Mobile\"; } // 如果以上条件都不满足,默认返回PC return \"PC\"; } /** * 获取访客 */ app.config.globalProperties.getVisitcode = function() { let visitcode = uni.getStorageSync(\'visitcode\'); if (!visitcode) { visitcode = \'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0,  v = c == \'x\' ? r : (r & 0x3 | 0x8); return v.toString(16); }); visitcode = visitcode.replace(/-/g, \"\"); uni.setStorageSync(\'visitcode\', visitcode); } return visitcode; }; /** * 显示失败提示框 */ app.config.globalProperties.showError = function (msg, callback) { uni.showModal({ title: \'友情提示\', content: msg, showCancel: false, success: function (res) { callback && callback(); } }); };/** * 显示失败提示框 */app.config.globalProperties.showWarn = function (msg, callback) { uni.showToast({ title: msg, duration: 2000,icon: \'none\' });}; /** * 显示成功提示框 */ app.config.globalProperties.showSuccess = function (msg, callback) { uni.showModal({ title: \'友情提示\', content: msg, showCancel: false, success: function (res) { callback && callback(); } }); }; /** * 是否是ios */ app.config.globalProperties.ios = function() { const u = navigator.userAgent.toLowerCase(); if (u.indexOf(\"like mac os x\") < 0 || u.match(/MicroMessenger/i) != \'micromessenger\') { return false; } return true; }; /** * 获取当前平台 */ app.config.globalProperties.isWeixin = function() { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == \"micromessenger\") { return true; } else { return false; } }; app.config.globalProperties.getPlatform = function(params) { let platform = \'wx\'; // #ifdef APP-PLUS if (uni.getSystemInfoSync().platform == \'android\') { platform = \'android\'; } else { platform = \'ios\'; } // #endif // #ifdef H5 if (this.isWeixin()) { platform = \'mp\'; } else { platform = \'h5\'; } // #endif return platform; }; app.config.globalProperties.topBarTop = function() { // #ifdef MP-WEIXIN return uni.getMenuButtonBoundingClientRect().top; // #endif // #ifndef MP-WEIXIN const SystemInfo = uni.getSystemInfoSync(); return SystemInfo.statusBarHeight; // #endif }; app.config.globalProperties.topBarHeight = function() { // #ifdef MP-WEIXIN return uni.getMenuButtonBoundingClientRect().height; // #endif // #ifndef MP-WEIXIN return 0 // #endif }; /* 小数点截取 */ app.config.globalProperties.subPrice = function(str, val) { let strs = String(str); if (val == 1) { return strs.substring(0, strs.indexOf(\".\")); } else if (val == 2) { let indof = strs.indexOf(\".\"); return strs.slice(indof + 1, indof + 3); } } /*转两位数*/ app.config.globalProperties.convertTwo = function(n) { let str = \'\'; if (n < 10) { str = \'0\' + n; } else { str = n; } return str; } app.config.globalProperties.yulan = function(e, i) { let image_path_arr = []; if (!Array.isArray(e)) { image_path_arr = [e]; } else { if (e[0].file_path) { e.forEach((item, index) => {  image_path_arr.push(item.file_path) }) } else { image_path_arr = e } } let picnum = i * 1; uni.previewImage({ urls: image_path_arr, current: picnum, }); } /* 截取小数点前后 */ app.config.globalProperties.subpoint = function(str, val) { let strs = String(str); if (val == 1) { return strs.substring(0, strs.indexOf(\".\")); } else if (val == 2) { let indof = strs.indexOf(\".\"); return strs.slice(indof + 1, indof + 3); } },app.config.globalProperties.getCurLevel=function(){ const pages = getCurrentPages(); return pages.length;}}export default global

request.js

function requestFun(app) {// get请求app.config.globalProperties._get = function(path, data, success, fail, complete) {data = data || {};data.token = uni.getStorageSync(\'token\') || \'\';uni.request({url: this.httpUrl + \'/\' + path,data: data,dataType: \'json\',method: \'GET\',header: {\'token\': uni.getStorageSync(\'token\') || \'\'},success: (res) => {if (res.statusCode === 500) {// this.showError(\'请求超时,请稍后重试\')this.showLoading = falsereturn false;}if (res.statusCode !== 200 || typeof res.data !== \'object\') {return false;}if (res.data.code === -2) {this.showError(res.data.msg, function() {uni.removeStorageSync(\'token\');this.gotoPage(\'/pages/index/index\', \'reLaunch\');})} else if (res.data.code === -1) {// 登录态失效, 重新登录this.doLogin();} else if (res.data.code === 0) {success && success(res.data);} else {success && success(res.data);}},fail: (res) => {fail && fail(res);if(res.errMsg==\"request:fail timeout\"){this.showError(\'请求超时,请稍后重试\')this.showLoading = false}},complete: (res) => {complete && complete(res);},});};// post请求 单个参数app.config.globalProperties._post = function(path, data, success, fail, complete) {data = data || {};data.token = uni.getStorageSync(\'token\') || \'\';uni.request({url: this.httpUrl + \'/\' + path,data: data,dataType: \'json\',method: \'POST\',header: {\'Content-Type\': \'application/x-www-form-urlencoded\',},success: (res) => {if (res.statusCode === 500) {this.showError(\'请求超时,请稍后重试\')this.showLoading = falsereturn false;}if (res.statusCode !== 200 || typeof res.data !== \'object\') {fail && fail(res);return false;}if (res.data.code === -1) {// 登录态失效, 重新登录this.doLogin();} else if (res.data.code === 0) {success && success(res.data);} else {success && success(res.data);}},fail: (res) => {fail && fail(res);if(res.errMsg==\"request:fail timeout\"){this.showError(\'请求超时,请稍后重试\')this.showLoading = false}},complete: (res) => {complete && complete(res);},});};// post请求 多个参数app.config.globalProperties._postBody = function(path, data, success, fail, complete) {data = data || {};uni.request({url: this.httpUrl + \'/\' + path,data: data,dataType: \'json\',method: \'POST\',header: {\'Content-Type\': \'application/json;charset=UTF-8\',\'token\': uni.getStorageSync(\'token\') || \'\'},success: (res) => {if (res.statusCode === 500) {// this.showWarn(\'请求超时,请稍后重试\')this.showLoading = falsereturn false;}if (res.statusCode !== 200 || typeof res.data !== \'object\') {fail && fail(res);return false;}if (res.data.code === -1) {// 登录态失效, 重新登录this.doLogin();} else if (res.data.code === 0) {success && success(res.data);} else {success && success(res.data);}},fail: (res) => {fail && fail(res);if(res.errMsg==\"request:fail timeout\"){this.showWarn(\'请求超时,请稍后重试\')this.showLoading = false}},complete: (res) => {complete && complete(res);},});}; app.config.globalProperties._upload = function(path, data, success, fail, complete) { uni.uploadFile({ url: this.httpUrl + \'/\' + path, filePath: data, name: \'file\', formData: {\'token\': uni.getStorageSync(\'token\') || \'\' }, success: (res) => { success && success(res.data); }, fail: (res) => { fail && fail(res);if(res.errMsg==\"request:fail timeout\"){this.showWarn(\'请求超时,请稍后重试\')this.showLoading = false} }, complete: (res) => { complete && complete(res); }, });};}export default requestFun

main.js

import config from \"./env/config.js\";import request from \"./utils/request.js\";import global from \'./utils/global.js\';// #ifndef VUE3import Vue from \'vue\'import App from \'./App\'Vue.config.productionTip = falseVue.prototype.$config = config; // 在 Vue 2 中将配置添加到原型链上App.mpType = \'app\'const app = new Vue({ ...App})request(app) // 如果 request 函数需要 config 参数,请确保传递它global(app)app.$mount()// console.log(\'vue2\',app)// 确保 uniapp 函数在此处被调用之前已经被正确导入和定义if (typeof uniapp === \'function\') { uniapp(app)} else { console.error(\'uniapp is not a function or not properly imported.\')}// #endif// #ifdef VUE3import { createSSRApp } from \'vue\'import App from \'./App.vue\'export function createApp() { const app = createSSRApp(App) // 全局配置 app.config.globalProperties.config = config app.config.globalProperties.httpUrl = config.app_url; app.config.globalProperties.imgUrl = config.img_url; request(app) // 如果 request 函数需要 config 参数,请确保传递它 global(app) return { app }}// console.log(\'vue3\',app)// #endif

更多技术分享请关注下面公众号⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️