微信小程序在 2.2.1 版本后增加了對 npm 包加載的支持,使得小程序支持使用 npm 安裝第三方包。
之前在微信開發者工具選擇“構建npm”會報錯“沒找到node_modules”目錄”,這是因為“打開的方式不正確”。
我們以安裝有贊的 vant
庫做例子
1. 初始化
現新建一個小程序,
在小程序根目錄中(miniprogram)執行:
npm init
輸入一些基本的信息,可以一直回車,按默認就可以,然后會生成一個package.json
文件
2. 安裝第三方庫
有贊文檔地址:https://youzan.github.io/vant-weapp/#/intro
接下來生成 package-lock.json
,記錄使用的第三方插件:
npm install --production
使用 --production
選項,可以減少安裝一些業務無關的 npm 包,從而減少整個小程序包的大小。
接着引入第三方組件:
npm i vant-weapp -S --production
引入得是有贊的UI組件,感覺不錯。會生成一個 node_modules
目錄。
3、構建 npm 包
node_modules 目錄不會參與編譯、上傳和打包中,所以小程序想要使用 npm 包必須走一遍“構建 npm”的過程,在最外層的 node_modules 的同級目錄下會生成一個 miniprogram_npm
目錄,里面會存放構建打包后的 npm 包,也就是小程序真正使用的 npm 包。
在微信開發者工具中點擊“工具-->構建npm”
最后,在根目錄下會生成如下目錄:
4、使用npm包
先在.json中引用:
{ "usingComponents": { "van-button": "vant-weapp/button/index", "van-progress": "vant-weapp/progress/index" } }
再在.wxml中使用:
<van-button type="danger">危險按鈕</van-button> <van-progress percentage="50" />
參考鏈接: