跳到主要内容
版本:v3

PWA Elements

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

PWA Elements

此 UI 是通过 Web 组件实现的。得益于 Shadow DOM 的特性,这些组件应该不会与您自己的 UI 产生冲突。

安装

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

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

导入 PWA Elements

npm install @ionic/pwa-elements

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

React

index.tsxindex.js

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

ReactDOM.render(<App />, document.getElementById('root'));

// 在应用首次渲染后调用元素加载器
defineCustomElements(window);

Angular

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

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

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic()
.bootstrapModule(AppModule)
.catch(err => console.log(err));

// 在平台启动后调用元素加载器
defineCustomElements(window);

通过脚本标签引入

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

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