NPM installation dependency in wechat applet

Time:2022-1-5

Click to go to the applet NPM official document

To install the dependent prerequisites, you need to generate a package JSON file

npm init  

Press enter all the way to generate:

NPM installation dependency in wechat applet

Then you can see package JSON has been generated

NPM installation dependency in wechat applet

Note: the package after initialization There are no dependencies in the JSON file, so trying to execute NPM install will not succeed

NPM installation dependency in wechat applet

Dependencies required for installation

For example, we are usingMobXAt this step, you can install it directlyMobXThe required dependencies.

We tried to install onevant-uitry

Click to go to the vant UI official document

npm i @vant/weapp -S --production

NPM installation dependency in wechat applet

Node after installation_ Modules folder, package Corresponding dependencies also appear in JSON

NPM installation dependency in wechat applet

It needs to be built after installation

  • Top left corner of wechat developer tool:toolBuilding NPM(if there is no dependency, clicking build will not succeed, and there will be a prompt that there are no items to build)
  • The results of the build are: generation andnode_modulesFolder of sibling directoryminiprogram_npm

Prompt for successful construction:

NPM installation dependency in wechat applet

After the build is completed, the dependent package can be used normally

For example, use the button component in the vant / web app package:

xxx.json

"usingComponents": {
  "van-button": "@vant/weapp/button"
},

xxx.wxml

<view class="usermotto">
  <van-button type="primary">demo</van-button>
  < van button type = "warning" > warning button < / Van button >
</view>

The effects are as follows:
NPM installation dependency in wechat applet

Add: Why build? Officially stated principles:

firstnode_modulesThe directory will not be involved in compiling, uploading and packaging, so if an applet wants to use NPM package, it must go through it againBuilding NPMThe process, in each copyminiprogramRootDeclared by developers withinpackage.jsonOutermost layer ofnode_modulesWill generate aminiprogram_npmDirectory, which will store the NPM package after the build package, that is, the NPM package actually used by the applet.