A starter template for TypeScript and WeChat with a detailed README describing how to use the two together.
A starter template for TypeScript and WeChat with a detailed README describing how to use the two together.
本教程将覆盖了基本的在使用微信JSSDK的网页上运用TypeScript的例子。
安装node.js。
拥有/申请网页将使用的域名以及能够使用Node.js的服务器。可参照Create a Node.js Application on Web App文档使用Azure。
完成微信开发文档步骤一:绑定域名。如果没有自己的公众号,可注册并使用微信测试号。记录下自己的appId, appsecret以及将使用的host URL。
建立一个新的npm package,
mkdir wxapp
cd wxapp
npm init在生成的package.json的scripts中添加以下scripts,
"scripts": {
"start": "node index.js",
"build-ts": "node ./node_modules/typescript/bin/tsc"
},安装需要的packages(express, ejs, request以及sha1),
npm install --save express ejs request sha1安装TypeScript以及之前安装的packages的类型定义。
npm install --save-dev typescript @types/node @types/express @types/request @types/sha1由于暂时DefinitelyTyped中并没有JSSDK相关的类型定义文件(.d.ts),请将本项目中的types文件夹(包含类型定义文件wechat.d.ts)复制到根目录(wxapp)中以便TypeScript获取JSSDK的类型定义。
在wxapp根目录下添加TypeScript配置文件tsconfig.json,
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
}
}可以根据项目的需求自行添加其他编译选项,比如strict。
对应通过config接口注入权限验证配置文档,调用微信JSSDK需要在自己的服务器后台向微信服务器获取jsapi_ticket并在前端通过wx.config进行验证。大致实现流程,
在根目录添加后台的初始文件index.ts,
…在index.ts中修改并填入自己的appId等等参数,
// Insert metadata
let appId = ''; // Insert your appId
let appsecret = ''; // insert your appsecret
let url = ''; // insert host url, e.g. http://wxapp.azurewebsites.net/
let nonceStr = 'hellotypescript'; // insert any string建立的node.js+express后台会通过getWXConfig向微信服务器获取jsapi_ticket,并将wx.config所需的参数通过ejs渲染(res.render(...))至客户端页面。
在index.ts中已定义将后台推至客户端的文件放入/views(包含所有需要ejs渲染的html文件)以及/public(其余的文件)文件夹。之后的步骤将覆盖前端的页面。
app.set('views', __dirname + '/views'); // set views dir
app.use(express.static('public')) // expose assets in /public在根目录下建立views文件夹并在其中添加index.html(推至客户端的主页),
WeChat TypeScript sample
index.html中引入了微信JSSDK(http://res.wx.qq.com/open/js/jweixin-1.0.0.js)以及将在客户端实现的简单的demo(/js/demo.js)。嵌入的JavaScript包含了之前渲染的getWXConfig提供的讯息并通过wx.config注入权限验证配置。
在根目录下建立public/js文件夹,并在其中添加demo.ts,
wx.ready(() => {
// open specifc location on map
wx.openLocation({
latitude: 0,
longitude: 0,
name: '',
address: '',
scale: 1,
infoUrl: ''
});
})
wx.error((err) => alert(err));在这个简化的例子中,我们仅使用wx.openLocation打开地图,但在demo.ts中你可以尝试使用任何在JsApiList中申请的API。
将.ts文件编译成.js,
npm run build-ts部署至服务器。
将页面所在的网址转换成二维码,打开微信扫一扫便可看到成果。
No open issues yet, or sync has not completed.