本文介绍一下如何使用搭建 typeScript uni-app 项目。注意,本文使用vue-cli在 VSCode 中进行操作,没有使用 HBuilderX。同时本文也会附带安装 pug 和 stylus,以及介绍在搭建过程中遇到的一些小问题。使用的软件版本如下:

  • 微信小程序开发者工具 v1.0.2
  • node 11.8.0
  • vue-cli 3.5.5
  • yarn 1.13.0

项目搭建

首先根据 文档 中介绍,执行如下命令来初始化一个新项目,最后是项目名称:

vue create -p dcloudio/uni-preset-vue my-ts-uni

确认过生成目录,稍等几秒初始化完成,就可以选择 默认模板 (TypeScript) 来创建 ts 项目了。过一会之后就会安装完成,完整的安装日志如下:

Vue CLI v3.5.5
? Generate project in current directory? Yes
✔  Fetching remote preset dcloudio/uni-preset-vue...


Vue CLI v3.5.5
✨  Creating project in /Users/admin/project/my-ts-uni.
🗃  Initializing git repository...
⚙  Installing CLI plugins. This might take a while...

yarn install v1.13.0
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
✨  Done in 40.41s.
🚀  Invoking generators...

Preset options:
? 请选择 uni-app 模板 默认模板(TypeScript)
📦  Installing additional dependencies...

yarn install v1.13.0
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
✨  Done in 18.58s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project my-ts-uni.
👉  Get started with the following commands:

 $ yarn serve

这样项目就已经创建好了,可以说非常简单了,虽然默认模板是用的 Vue. extend() 进行编写,但是项目中已经自动下好了 vue-property-decorator,很简单的就可以修改成 class 风格。

<script lang="ts">
// class 风格的 App.vue
import { Vue, Component } from 'vue-property-decorator'

@Component({})
export default class App extends Vue {
    mpType = 'app'
    onLaunch() {
        console.log('App Launch')
    }
    onShow() {
        console.log('App Show')
    }
    onHide() {
        console.log('App Hide')
    }
}
</script>

运行到微信小程序

由于我主要是开发到微信小程序平台,所以这里就以微信小程序作为示例,在package.json里可以看到如下命令,其中微信小程序的相关命令已经被我列了出来,想运行到其他平台只需要检查自己的package.json即可:

"scripts": {
    "serve": "npm run dev:h5",
    "build": "npm run build:h5",
    ...
    "build:mp-weixin": "cross-env NODE_ENV=production UNI_PLATFORM=mp-weixin vue-cli-service uni-build",
    ...
    "dev:mp-weixin": "cross-env NODE_ENV=development UNI_PLATFORM=mp-weixin vue-cli-service uni-build --watch",
   ...
}

可以看到想要默认的开发和打包目标是 h5,和标准 vue 项目的开发模式并无区别,这里不再多提。由于我们想要编译到微信小程序,所以这里执行yarn dev:mp-weixin启动开发服务器,稍等片刻就能看到如下输出:
在这里插入图片描述
然后你就可以在项目里找到 dist/dev/mp-weixin 目录,这个就是编译完成的微信小程序代码,接下来只需要启动微信小程序开发者工具打开该目录就可以了:
由于 dev 服务器会自动执行差量更新,而微信小程序也会监测代码修改并自动刷新,所以我们编写完代码后直接保存就可以在小程序开发工具里看到修改成果了,倒也挺方便。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐