React Native Android Native Module
🍱Framework
javascript
react-native
You might wonder how all of these open-source extensions to RN are created. Here is my workflow for creating a native-module for android
How to create an Android Native Module
Create it
-
Create a project
react-native init myModuleInsideTestApp - Open the Android project in
myModuleWithApp/androidin AndroidStudio. - Create a new Java package and follow the official instructions to create the skeleton of the app.
- Link the package to the JS part of your React Native App as you would any other external React Native Package.
- Call the package inside your
index.android.jsfile or even create a larger app depending on your module.
Bundle your new native module to an npm package
- Create a new folder
myModuleand create an android folder within it. -
Move your code from inside the
android/appfolder intomyModule/android/cp -R my-test-app/android/app/ my-npm-module/android/ - Create a
package.jsonwith$ npm initand following the prompts. If you don’t know the answer to a question, just hit enter. You can then edit thepackage.jsonlater. - Add
.npmignorefor folders you want to ignore in the final dependency. For exampleandroid/build/should go in here.
Test your bundled npm package
-
Create a
myModuleTestAppfolder projectreact-native init myModuleTestApp -
Include the npm package
npm install --save ../path/to/folder/myModule - Link the app as with any other external module and include all the other required things there might be..
- Test-run the app
Publish your npm package
- If it’s an open-source project, host it on Github and add the repository url to your
package.jsonfile. - Publish your module to npm
How to update a native module
Idea:
- Make changes in the app with the local version of your module. Test it there.
- Copy/paste the changed Java files into the separate npm module folder.
-
In the Test-App, do the following:
npm uninstall --save my_module npm prune my_module # Removes it from node_modules folder npm install ./path/to/module/my_moduleThen test the app.
- Increase the version number, push to Github and publish the updated npm module
Discuss on Twitter ● Improve this article: Edit on GitHub