微前端: single-spa 创建跨框架共享的JavaScript逻辑

公用的 js 逻辑复用
更新于: 2023-03-24 22:08:29

创建 tools

利用 spa 创建 tools 应用

tools/src/jswork-tools 代码

// Anything exported from this file is importable by other in-browser modules.
export function sayHi(msg) {
  console.log(`%cTOOLS: hahaha!!! ${msg}`, 'color: red;');
}

在 react 中使用

import { useState, useEffect } from "react";

const useTools = () => {
  const [tool, setTool] = useState();
  useEffect(() => {
    System.import("@jswork/tools").then(setTool);
  }, []);
  return tool;
};

export default () => {
  console.log("home mouthing");
  const tools = useTools();
  if (tools) tools.sayHi('abdd');
  return (
    <div>
      <h1>Home</h1>
      <p>
        This is a simple single-spa application built with React, React Router,
      </p>
    </div>
  );
};

参考