微信小程序创建

小程序基本目录结构

uni-app
├─ App.vue                                配置App全局样式,监听应用生命周期
├─ index.html                             H5端页面
├─ main.js                                Vue初始化入口文件
├─ manifest.json                          配置appid、应用名称、logo、版本等打包信息
├─ pages                                  业务页面文件存放的目录
│    └─ index
│           └─ index.vue                  index页面
├─ pages.json                             配置页面路由、导航栏、tabBar等页面类信息
├─ static                                 存放应用引用的本地静态资源的目录(注意:静态资源只能存放于此)
└─ uni.scss                               uni-app内置的常用样式变量

小程序创建基本配置项

配置easycom

npm i @dcloudio/uni-ui   或   yarn add @dcloudio/uni-ui

使用 npm 安装好 uni-ui 之后,需要配置 easycom 规则,让 npm 安装的组件支持 easycom

打开项目根目录下的 pages.json 并添加 easycom 节点:

// pages.json
{        //组件自动引入规则
	"easycom": {
                 //是否开启自动扫描
		"autoscan": true,
                 //以正则方式自定义组件规则
		"custom": {
			// uni-ui 规则如下配置
			"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
		}
	},
	
	// 其他内容
	pages:[
		// ...
	]
}

配置ts类型

npm i @uni-helper/uni-ui-types

配置 tsconfig.json,确保 compilerOptions.types 中含有 @dcloudio/types 和 @uni-helper/uni-ui-types 且 include 包含了对应的 vue 文件

//tsconfig.json
{
  "compilerOptions": {
    "types": ["@dcloudio/types", "@uni-helper/uni-ui-types"]
  },
  "vueCompilerOptions": {
    "experimentalRuntimeMode": "runtime-uni-app"
  },
  "include": ["src/**/*.vue"]
}

小程序端持久化

// TODO: 持久化
  {
    //网页端配置
    // persist: true,
    //小程序端配置
    persist: {
      storage: {
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        }
      }
    }
  },

组件自动导入示例

静态结构:src/components/XtxSwiper.vue

参考配置:

{
  // 组件自动引入规则
  "easycom": {
    // 是否开启自动扫描 @/components/$1/$1.vue 组件
    "autoscan": true,
    // 以正则方式自定义组件匹配规则
    "custom": {
      // uni-ui 规则如下配置
      "^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue",
      // 以 Xtx 开头的组件,在 components 目录中查找
      "^Xtx(.*)": "@/components/Xtx$1.vue"
    }
  }
}

 

全局组件类型声明:

// src/types/components.d.ts
import XtxSwiper from './XtxSwiper.vue'
declare module 'vue' {
  export interface GlobalComponents {
    XtxSwiper: typeof XtxSwiper
  }
}