Garfish 是字节跳动开源的微前端框架,旨在应对现代 Web 应用在前端生态繁荣与应用日益复杂化背景下的挑战。本文将介绍如何使用 Garfish,提供代码示例,并与另一流行的微前端框架 Qiankun 进行对比分析。
首先,安装 Garfish 核心库:
- npm install @garfish/core --save
-
创建主应用的入口文件,如 index.js 或 main.js,并初始化 Garfish:
- import Garfish from '@garfish/core';
-
- const garfish = new Garfish({
- router: {
- historyType: 'hash',
- publicPath: '/',
- routes: [
- {
- path: '/app1',
- microApp: {
- name: 'app1',
- entry: '//localhost:8081',
- container: '#root',
- activeRule: (location) => location.pathname === '/app1',
- },
- },
- {
- path: '/app2',
- microApp: {
- name: 'app2',
- entry: '//localhost:8082',
- container: '#root',
- activeRule: (location) => location.pathname === '/app2',
- },
- },
- ],
- },
- });
-
- garfish.start();
-
每个微应用都应有独立的构建流程,以下是基于 localhost:8081 运行的 Vue 应用示例:
在微应用中,暴露必要的 API 供 Garfish 调用:
- // app1/main.js
- import { bootstrap, mount, unmount } from '@garfish/runtime-vue';
- import App from './App.vue';
-
- bootstrap(App).then(mount(App)).catch(console.error);
-
- window.unmount = unmount;
-
使用 Webpack 或 Rollup 等工具来打包微应用。例如,使用 Webpack:
- // webpack.config.js
- module.exports = {
- entry: './src/index.js',
- output: {
- filename: 'bundle.js',
- publicPath: '/',
- },
- // 其他配置...
- };
-
打包完成后,将微应用部署到相应的服务器,如 localhost:8081。
Garfish 支持包括 Vue、React、Angular 在内的多种前端框架,开发者可以根据自身的技术栈选择合适的框架。
Garfish 内置 VM 沙箱机制,确保微应用之间的资源隔离,避免全局变量污染。
Garfish 为微前端开发提供了强大的工具集,能够有效解决跨团队协作、技术体系多样化等问题。Garfish 与 Qiankun 各有优势,选择框架时应根据项目的具体需求和技术偏好。通过遵循本指南,你可以充分利用 Garfish 的强大功能,构建高效、可维护的微前端系统。