跳到主要内容
版本:v5

PWA 元素组件

部分 Capacitor 插件(如 CameraToast)在非原生环境下运行时提供了基于网页的界面。例如,调用 Camera.getPhoto() 方法时,在网页端会加载一个响应式的照片拍摄界面:

PWA 元素组件

这些界面是通过 Web 组件实现的。由于这些元素被封装在 Shadow DOM 中,因此不会与您自己的界面产生冲突。

安装指南

要启用这些控件,您需要在应用中添加 @ionic/pwa-elements 依赖。

典型安装方式包括导入包并注册元素组件,或者在应用的 index.html 文件中添加脚本标签:

导入 PWA 元素组件

npm install @ionic/pwa-elements

根据您选择的前端框架,导入元素加载器并在合适时机调用:

React

main.tsxindex.tsxindex.js

import { defineCustomElements } from '@ionic/pwa-elements/loader';

// 在渲染调用前执行元素加载
defineCustomElements(window);
Vue

main.ts

// 在 createApp() 调用之前
import { defineCustomElements } from '@ionic/pwa-elements/loader';
defineCustomElements(window);
Angular

main.ts

import { defineCustomElements } from '@ionic/pwa-elements/loader';
// 在 bootstrapModule/bootstrapApplication 调用前执行元素加载
defineCustomElements(window);
if (environment.production) {
enableProdMode();
}

通过脚本标签引入

您也可以在 index.html 中通过脚本标签引入 PWA 元素组件,但请注意这种方式不支持离线场景:

<script
type="module"
src="https://unpkg.com/@ionic/pwa-elements@latest/dist/ionicpwaelements/ionicpwaelements.esm.js"
></script>
<script
nomodule
src="https://unpkg.com/@ionic/pwa-elements@latest/dist/ionicpwaelements/ionicpwaelements.js"
></script>