跳到主要内容

vite-vue3-umd

2024年03月21日
柏拉文
越努力,越幸运

一、认识


二、语法


2.1 src/main.ts

import App from "./App.vue";
import createRouter from "./router";
import Vue, { createApp } from "vue";
import packageInfo from "../package.json";

interface PropsType {
base: string;
mode: "hash" | "history";
container: Element | string;
}

let instance: Vue.App<Element>;

function render(props: PropsType) {
const { base, mode, container } = props;
instance = createApp(App);
instance.use(createRouter(mode, base));
instance.mount(container);
}

if (!window.__POWERED_BY_QIANKUN__) {
const props: PropsType = {
base: "/",
mode: "history",
container: `#${packageInfo.name}`,
};
render(props);
}

export async function bootstrap(): Promise<void> {
console.log(`${packageInfo.name} bootstrap 阶段`);
}

export async function mount(props: PropsType): Promise<void> {
console.log(`${packageInfo.name} mount 阶段`, props);
render(props);
}

export async function unmount(): Promise<void> {
console.log(`${packageInfo.name} unmount 阶段`);
}

2.2 src/router.ts

import {
createRouter,
createWebHashHistory,
createWebHistory,
RouteRecordRaw,
Router,
} from "vue-router";

import Home from "./pages/Home.vue";
import About from "./pages/About.vue";

const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
component: About,
},
];

export default function create(mode?: string, base?: string): Router {
return createRouter({
history:
mode === "history" ? createWebHistory(base) : createWebHashHistory(base),
routes,
});
}

2.3 src/App.vue

<template>
<div>
<h3>Micro-App-Vue3 微应用</h3>
<div>
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
</div>
<router-view />
</div>
</template>

<script setup lang="ts"></script>

<style scoped></style>

2.4 index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Micro-App-Vue3</title>
</head>
<body>
<div id="micro-app-vue3"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

2.5 vite.config.ts

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import packageInfo from "./package.json";
import { visualizer } from "rollup-plugin-visualizer";

export default ({ mode }: { mode: string }) => {
return defineConfig({
base:
mode === "production"
? `https://bolawen.github.io/MicroFrontEnd/QianKun/${packageInfo.name}/`
: "/",
plugins: [vue()],
server: {
port: "8081",
},
build: {
assetsDir: "",
outDir: "output",
cssCodeSplit: false,
target: "es2015",
rollupOptions: {
input: "src/main.ts",
preserveEntrySignatures: "strict",
plugins: [visualizer({ open: false })],
output: {
name: `${packageInfo.name}`,
format: "umd",
entryFileNames: `${packageInfo.name}.[format].[hash].js`,
},
},
},
});
};