使用mpvue+typescript搭建前端小程序项目
项目搭建
mpvue官网五分钟教程:http://mpvue.com/mpvue/
创建项目命令:
全局安装 vue-cli
$ npm install --global vue-cli
创建一个基于 mpvue-quickstart 模板的新项目
$ vue init mpvue/mpvue-quickstart my-project
默认安装即可
$ cd my-project
$ npm install
#启动构建
$ npm run dev
启动并预览项目
预览项目是否搭建成功。打开微信开发工具,导入项目,选择刚刚搭建的项目文件夹,选择 dist/wx,确认,就能看到效果啦(注释:这里就不贴图了,搭建项目后,没用的文件删的太快了,啊哈哈!)
配置typescript
1 安装依赖项
安装 vue 与装饰器,mpvue-loader目前支持用TypeScript来写,功能还在完善中(WIP)。需要搭 配vue-property-decorator来使用。
$ npm install --save vue vue-property-decorator
安装 typescript
$ npm install --save typescript@3.9.6
安装 typescript 所需loader(注意存在版本兼容问题,需下载指定版本ts-loader与awesome-typescript-loader最新版目前不兼容webpack4以下版本)
$ npm install --save ts-loader@3.1.1 awesome-typescript-loader@4.0.1
安装声明文件@types/node @types/weixin-app
$ npm install --save @types/node @types/weixin-app
安装vue-class-component
$ npm install --save vue-class-component
(注意:在安装依赖项时,如果提升warn,可以详细阅读一下,注意出现 You must install peer dependcies yourself时,必须自己安装,根据提示的需要,进行对应安装就好了,问题不大!)
2.安装官方微信小程序定义文件
安装官方微信小程序定义文件:https://github.com/wechat-miniprogram/api-typings#%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%AE%9A%E4%B9%89%E6%96%87%E4%BB%B6
此为微信小程序 API 的 TypeScript 类型定义文件,请时刻关注官方最新版本
$ npm install miniprogram-api-typings
3.让TypeScript识别Vue文件
在src目录下,新建一个vue-shim.d.ts文件,写入下面的代码,让TypeScript识能别Vue文件
declare module “*.vue”{
import Vue from ‘vue’
export default Vue;
}
4.配置webpack 3.x
-
在build文件下找到webpack.base.conf.js文件(这是项目打包的配置文件)
在extensions中加入ts文件格式 -
在module中的rules中加入ts的loader
代码:{ test: /\.tsx?$/, exclude: /node_modules/, use: [ 'babel-loader', { loader: 'mpvue-loader', options:Object.assign({checkMPEntry: true}, vueLoaderConfig)//与同级的js中对应项值一致 }, { // loader: 'ts-loader', loader: 'awesome-typescript-loader', options: { // errorsAsWarnings: true, useCache: true, } } ] },
5.**增加typescript配置 **
在项目的根目录下,新建一个tsconfig.json文件,写入typoescript配置(也可以参照官网:https://www.tslang.cn/docs/handbook/tsconfig-json.html)
{
"compilerOptions": {
// 与 Vue 的浏览器支持保持一致
"target": "es2015",
// 这可以对 `this` 上的数据属性进行更严格的推断
"strict": true,
// 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake:
"module": "es2015",
"moduleResolution": "node",
"baseUrl": "./",
"outDir": "./dist/",
"paths": {
"vue": [
"node_modules/mpvue"
],
"@/*": [
"src/*"
]
},
"types": [
"@types/weixin-app",//声明文件
"@types/node"
],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"skipLibCheck": true,
"strictPropertyInitialization": false,
"experimentalDecorators": true
},
"include": [
"./src/**/*"
],
"exclude": [
"node_modules"
],
"typeAcquisition": {
"enable": true
}
}
6.将webpack.base.config.js文件中的入口文件名后缀改成.ts
function getEntry (rootSrc) {
var map = {};
glob.sync(rootSrc + '/pages/**/main.ts')
.forEach(file => {
var key = relative(rootSrc, file).replace('.ts', '');
map[key] = file;
})
return map;
}
const appEntry = { app: resolve('./src/main.ts') }
const pagesEntry = getEntry(resolve('./src'), 'pages/**/main.ts')
const entry = Object.assign({}, appEntry, pagesEntry)
7.将 src/main.js 文件修改为 main.ts ,并添加代码
// main.ts
import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator';
import { VueConstructor } from "vue";
interface IMpVue extends VueConstructor {
mpType: string
}
// 添加小程序hooks http://mpvue.com/mpvue/#_4
Component.registerHooks([
// app
'onLaunch', // 初始化
'onShow', // 当小程序启动,或从后台进入前台显示
'onHide', // 当小程序从前台进入后台
// pages
'onLoad', // 监听页面加载
'onShow', // 监听页面显示
'onReady', // 监听页面初次渲染完成
'onHide', // 监听页面隐藏
'onUnload', // 监听页面卸载
'onPullDownRefresh', // 监听用户下拉动作
'onReachBottom', // 页面上拉触底事件的处理函数
'onShareAppMessage', // 用户点击右上角分享
'onPageScroll', // 页面滚动
'onTabItemTap', //当前是 tab 页时, 点击 tab 时触发 (mpvue 0.0.16 支持)
])
Vue.config.productionTip = false
// 在这个地方引入是为了registerHooks先执行
const MyApp = require('./App.vue').default as IMpVue
const app = new Vue(MyApp)
app.$mount()
8.App.vue中引入main.ts文件
//app.vue中 mpvue-loader目前支持用TypeScript来写,功能还在完善中(WIP)。目前实现了用<script lang="ts" src="./xx.ts"></script>这种方式的自动识别
<script lang='ts' src="./app.ts"></script>
<style></style>
重新打包npm run build
npm start 启动项目,编译通过,配置完成,下面接着说说typescript如何在mpvue中写法。
目录结构:
index.vue文件
<template>
<div>我的名字:{{userinfo.name}}</div>
<div>我的年龄:{{userinfo.age}}</div>
<div>我的性别:{{userinfo.gender==0?'男':'女'}}</div>
<div>我的爱好:{{userinfo.like}}</div>
</template>
//当前文件下的index.ts文件
<script lang='ts' src='./index.ts'></script>
.index.ts文件
import { Vue, Component } from 'vue-property-decorator'
@Component({
name:'userinfo'
})
class Userinfo extends Vue{
userinfo: object = {
name: string = '张三',
age: number = 20,
gender: number = 0,
like: string = '在下性别男,爱好女!'
}
}
export default Userinfo
.main.ts文件
import Vue from 'vue'
import Index from './index.vue'
const index = new Vue(Index)
index.$mount()
.main.json文件
{
"navigationBarTitleText": "个人信息",
}
大功告成,希望给大家带来帮助,啦啦啦,点个赞咯!