跳到主要内容
版本:v8

PWA Elements

一些 Capacitor 插件,例如 CameraToast,在非原生环境下运行时提供基于 Web 的 UI。例如,在 Web 端调用 Camera.getPhoto() 会加载一个响应式的拍照体验:

PWA Elements

这些 UI 是使用 Web 组件实现的。由于这些元素被 Shadow DOM 封装,它们应该不会与你自己的 UI 产生冲突。

安装

要启用这些控件,你必须将 @ionic/pwa-elements 添加到你的应用中。

典型的安装方式包括导入包并注册元素,或者在你的应用 index.html<head> 中添加一个 script 标签:

导入 PWA Elements

npm install @ionic/pwa-elements

然后,根据你选择的框架,导入元素加载器并在合适的时机调用它:

React

main.tsxindex.tsxindex.js

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

// 在 render 调用之前调用元素加载器
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();
}

通过 script 标签引入

PWA Elements 可以通过你 index.html 中的 script 标签引入。但请注意,这种方式在离线场景下无法工作:

<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>