Usage of npm packages in cordova / phonegap

2019-08-06 09:46发布

I’m trying to add a package to my Cordova project using NPM, but either I’m doing something terribly wrong or I’m not getting the way it should work… I’m using the latest version of Cordova (v3.5.0). I have created an application:

cordova create TestApp
cd TestApp
cordova platform add android
cordova run android

Everything works perfectly, and the app appears on my Android device. Now I want to add the package ‘pako’ to my app: https://github.com/nodeca/pako. I’m still in the same directory (see above) and I enter “npm install pako”. The package is installed in “/node_modules/”.

However, when I build my application for Android (cordova build android / cordova run android / cordova prepare), none of my installed packages (in the “/node_modules/” directory) is copied to the platform specific folder “platforms/android/….”. In other words, how to use a npm package in a Cordova / Phonegap application? Shouldn’t this package be copied automatically by the cordova cli to the right platform?

Is this possible at all? Or do I have to create a manual build script using Grunt for example when I want to use npm packages? Since I can’t find any examples, I have the idea that I’m completely on the wrong track, so if anyone has a little hint to help me in the right direction, I would be very grateful.

Thanks in advance!

标签: cordova npm
2条回答
闹够了就滚
2楼-- · 2019-08-06 09:46

Adding all installed modules is usually not what you would want because they might contain other dependencies that are not actually used in the application (like testing tools or grunt tasks). While you can use npm to download dependencies and to keep them up to date, you still need to include them manually in your app.

Grunt and grunt-contrib-copy (if you want separate files) or grunt-contrib-concat (if you want a single file, usually better for performance) would be one solution. Another one would be Browserify, which has support for npm modules built in.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-06 10:04

This is possible by using a hook triggered before_prepare.

See https://stackoverflow.com/a/46615080/2728710

查看更多
登录 后发表回答