id: ecosystem-preact title: single-spa-preact

sidebar_label: Preact

single-spa-preact是个帮助类库,通过实现生命周期函数 (bootstrap, mount and unmount),可以帮助开发者在single-spa中快速注册 Preact应用。仓库地址见 single-spa-preact github

安装

  1. npm install --save preact

快速开始

在项目的入口文件添加如下代码:

  1. import preact from 'preact';
  2. import rootComponent from './path-to-root-component.js';
  3. import singleSpaPreact from 'single-spa-preact';
  4. const preactLifecycles = singleSpaPreact({
  5. preact,
  6. rootComponent,
  7. domElementGetter: () => document.getElementById('main-content'),
  8. });
  9. export const bootstrap = preactLifecycles.bootstrap;
  10. export const mount = preactLifecycles.mount;
  11. export const unmount = preactLifecycles.unmount;

选项

在调用singleSpaPreact(opts)方法时,opts参数会将所有选项传递给single-spa-preact。选项如下:

  • preact: (必填) Preact对象,一般挂载在window上,也可以通过require('preact')import preact from 'preact' 引入
  • rootComponent: (必填) 将要渲染的Preact应用根组件
  • domElementGetter: (必填) 这个参数是个函数,没有入参,返回一个DOM元素。这个DOM元素会作为该Preact应用初始化、挂载和卸载的对象