Capacitor自定义插件编写2025-08-21

插件生成器

准备好开始了吗?Capacitor 有一个插件生成器,您可以使用它来开始处理插件。

在继续之前,您可能需要确保您使用的是最新的 Node LTS 版本和 npm 6+。

在新终端中,运行以下命令:

npm init @capacitor/plugin@latest

生成器将提示你输入。还可以提供命令行选项(请参阅 GitHub 存储库)。


√ What should be the npm package of your plugin?

... scanner

√ What directory should be used for your plugin?

... scanner

√ What should be the Package ID for your plugin?

    Package IDs are unique identifiers used in apps and plugins. For plugins,

    they're used as a Java namespace. They must be in reverse domain name

    notation, generally representing a domain name that you or your company owns.

... com.mycompany.plugins.example

√ What should be the class name for your plugin?

... Scanner

√ What is the repository URL for your plugin?

... https://github.com/<user>/<repo>

√ (optional) Who is the author of this plugin?

... y

√ What license should be used for your plugin?

» MIT

√ Enter a short description of plugin features.

... scanner

Installing dependencies. Please wait...


使用WebStorm打开项目  scanner 项目编辑 

web.ts


使用AndroidStudio 打开项目   scanner/android 编辑  

com.mycompany.plugins.example


编辑完成后 回到 WebStorm 项目 scanner   根目录 进行编译

"scripts": {

"build":"npm run clean && npm run docgen && tsc && rollup -c rollup.config.mjs"

},

然后打包  npm pack

打包后会生成  scanner-0.0.1.tgz

将该文件 复制到 Ionic项目的根目录

 执行npm安装   

这个地方用的是pnpm 速度快

pnpm add ./scanner-0.0.1.tgz

卸载的

pnpm remove scanner


npx cap sync

npx cap sync android (上面的不知道啥原因,执行完安卓执行会提示注册不到插件)


安装完成后就可以引用插件里面的方法  echo 


<script setup lang="ts">


import { Scanner }from 'scanner';


onMounted(() => {

Scanner.echo('你好!')

});

主项目的安卓项目需要手动注册插件

android/settings.gradle 增加如下配置

include':scanner'

project(':scanner').projectDir =new File('../node_modules/scanner/android')

applyfrom:'capacitor.settings.gradle'


android/app/build.gradle 增加如下配置

dependencies{


implementation project(':scanner')

}


Ionic项目执行

ionic cap copy

ionic cap sync

ionic cap run android -l --external

然后会开启虚拟机 看效果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容