Skip to content

Commit

Permalink
fix hot-update
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronlamz committed Aug 31, 2024
1 parent c24e779 commit 0632851
Show file tree
Hide file tree
Showing 7 changed files with 168 additions and 99 deletions.
107 changes: 57 additions & 50 deletions navpress.config.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,77 @@
// config/index.js
export default {
title: 'My Static Site Generator',
description: 'A simple static site generator with configurable navigation',
logo: '/navpress/images/logo.svg',
github: 'https://github.com/aaronlamz/navpress',
base:'/navpress/',
title: "我的开发导航",
description: "A simple static site generator with configurable navigation",
logo: "/navpress/images/logo.svg",
github: "https://github.com/aaronlamz/navpress",
base: "/navpress/",
meta: {
title: 'My Navpress',
description: 'Navpress - a simple static site generator with configurable navigation',
keywords: 'static site, generator, navpress, vue',
author: 'aaronlamz',
title: "My Navpress",
description:
"Navpress - a simple static site generator with configurable navigation",
keywords: "static site, generator, navpress, vue",
author: "aaronlamz",
},
sidebar: [
{
text: 'Home',
link: '/',
{
text: "Web",
link: "/",
items: [
{
text: 'Group 1',
link: '#group1',
text: "前端",
link: "#group1",
items: [
{ text: 'Child 1', link: 'https://example.com/child1' },
{ text: 'Child 2', link: 'https://example.com/child2' },
{ text: 'Child 2', link: 'https://example.com/child2' },
]
{ text: "Child 1", link: "https://example.com/child1" },
{ text: "Child 2", link: "https://example.com/child2" },
{ text: "Child 2", link: "https://example.com/child2" },
],
},
{
text: 'Group 2',
link: '#group2',
text: "设计",
link: "#group2",
items: [
{ text: 'Child 3', link: 'https://example.com/child3' },
{ text: 'Child 4', link: 'https://example.com/child4' },
{ text: 'Child 2', link: 'https://example.com/child2' },
]
{ text: "Child 3", link: "https://example.com/child3" },
{ text: "Child 4", link: "https://example.com/child4" },
{ text: "Child 2", link: "https://example.com/child2" },
],
},
],
},
{
text: "效率工具",
link: "/efficient",
expanded: true,
items: [
{
text: 'Group 3',
link: '#group3',
items: [
{ text: 'Child 3', link: 'https://example.com/child3' },
{ text: 'Child 4', link: 'https://example.com/child4' },
]
text: "Group A",
link: "#groupA",
items: [{ text: "Child A1", link: "https://example.com/childA1" }],
},
],
},
{
text: "AI 资源",
link: "/ai",
expanded: true,
items: [
{
text: 'Group 4',
link: '#group4',
items: [
{ text: 'Child 3', link: 'https://example.com/child3' },
{ text: 'Child 4', link: 'https://example.com/child4' },
]
}
]
text: "Group A",
link: "#groupA",
items: [{ text: "Child A1", link: "https://example.com/childA1" }],
},
],
},
{
text: 'About',
link: '/about',
expanded: false,
{
text: "副业有道",
link: "/second-job",
expanded: true,
items: [
{
text: 'Group A',
link: '#groupA',
items: [
{ text: 'Child A1', link: 'https://example.com/childA1' },
]
}
]
text: "Group A",
link: "#groupA",
items: [{ text: "Child", link: "https://example.com/childA1" }],
},
],
},
],
}
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "navpress",
"version": "1.0.0-beta.5",
"version": "1.0.0-beta.6",
"description": "Easy navigation website generator",
"main": "index.js",
"type": "module",
Expand Down
8 changes: 3 additions & 5 deletions src/App.vue
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<template>
<div id="app" class="dark:bg-gray-900 min-h-screen flex flex-col">
<Navbar :nav="config.nav" />
<Navbar :nav="$config.nav" />
<div class="main-container flex flex-1 overflow-hidden">
<Sidebar :sidebar="config.sidebar" class="sidebar-container bg-gray-100 dark:bg-gray-800" />
<Sidebar :sidebar="$config.sidebar" class="sidebar-container bg-gray-100 dark:bg-gray-800" />
<div class="content-container flex-1 overflow-y-auto p-6 dark:bg-gray-900">
<router-view />
<FooterComponent />
Expand All @@ -23,9 +23,7 @@ export default {
FooterComponent
},
data() {
return {
config: __USER_CONFIG__
}
return {}
}
}
</script>
Expand Down
6 changes: 3 additions & 3 deletions src/components/Navbar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
<nav class="bg-white dark:bg-gray-900 shadow-md fixed w-full z-50">
<div class="container mx-auto flex justify-between items-center py-4 px-6">
<div class="flex items-center">
<img :src="config.logo" alt="Logo" class="h-10 w-auto mr-3" />
<img :src="$config.logo" alt="Logo" class="h-10 w-auto mr-3" />
<span class="text-xl font-semibold text-gray-900 dark:text-white">
{{ config.title }}
{{ $config.title }}
</span>
</div>
<!-- <ul class="hidden md:flex space-x-6">
Expand All @@ -13,7 +13,7 @@
</li>
</ul> -->
<div class="flex items-center">
<a v-if="config.github" :href="config.github" target="_blank" rel="noopener noreferrer" class="ml-4">
<a v-if="$config.github" :href="$config.github" target="_blank" rel="noopener noreferrer" class="ml-4">
<svg class="w-6 h-6 text-gray-900 dark:text-gray-300 hover:text-blue-500 dark:hover:text-blue-400"
fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path
Expand Down
51 changes: 36 additions & 15 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,45 @@
import { createSSRApp, createApp as createCSRApp } from 'vue'
import App from './App.vue'
import router from './router/index.js' // 明确导入文件
import './assets/style/index.css'
import { createSSRApp, createApp as createCSRApp, reactive } from 'vue';
import App from './App.vue';
import { createRouterInstance } from './router';
import './assets/style/index.css';

// 获取全局配置
const config = typeof __USER_CONFIG__ !== 'undefined' ? __USER_CONFIG__ : {};
const initialConfig = typeof __USER_CONFIG__ !== 'undefined' ? __USER_CONFIG__ : {};
const userConfig = reactive(initialConfig); // 使用 reactive 创建响应式的配置对象

console.log('Initial userConfig:', userConfig);

export function createApp() {
const app = createSSRApp(App)
app.use(router)
const app = createSSRApp(App);
const router = createRouterInstance(userConfig);
app.use(router);
// 将配置挂载到全局
app.config.globalProperties.$config = config;
return { app, router }
app.config.globalProperties.$config = userConfig;
return { app, router };
}

if (typeof window !== 'undefined') {
const app = createCSRApp(App)
app.use(router)
// 将配置挂载到全局
app.config.globalProperties.$config = config;
app.mount('#app')
}
let app;
let router;

const initializeApp = () => {
app = createCSRApp(App);
router = createRouterInstance(userConfig);
app.use(router);
// 将配置挂载到全局
app.config.globalProperties.$config = userConfig;
app.mount('#app');
};

initializeApp();

// 监听 Vite 的自定义事件更新配置
if (import.meta.hot) {
import.meta.hot.on('config-updated', (newConfig) => {
Object.assign(userConfig, newConfig); // 更新响应式对象
console.log('Config updated:', userConfig);
app.unmount();
initializeApp();
});
}
}
53 changes: 37 additions & 16 deletions src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,43 @@ import LinksPage from '../pages/LinksPage.vue'

const isServer = typeof window === 'undefined';

const generateRoutes = (sidebar) => {
return sidebar.map(item => ({
path: item.link,
component: LinksPage,
props: {
items: item.items || [],
title: item.text
}
}))
}
// const generateRoutes = (sidebar) => {
// return sidebar.map(item => ({
// path: item.link,
// component: LinksPage,
// props: {
// items: item.items || [],
// title: item.text
// }
// }))
// }

// const routes = generateRoutes(__USER_CONFIG__.sidebar)

// const router = createRouter({
// history: isServer ? createMemoryHistory() : createWebHashHistory(), // 使用 hash 模式
// routes,
// })

const routes = generateRoutes(__USER_CONFIG__.sidebar)
// export default router

const router = createRouter({
history: isServer ? createMemoryHistory() : createWebHashHistory(), // 使用 hash 模式
routes,
})
export function createRouterInstance(config) {
const generateRoutes = (sidebar) => {
return sidebar.map(item => ({
path: item.link,
component: LinksPage,
props: {
items: item.items || [],
title: item.text
}
}));
};

const routes = generateRoutes(config.sidebar);

return createRouter({
history: isServer ? createMemoryHistory() : createWebHashHistory(), // 使用 hash 模式
routes,
});
}

export default router
40 changes: 31 additions & 9 deletions vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const loadUserConfig = async () => {

try {
await fs.access(configPath);
userConfig = await import(configPath).then(module => module.default);
userConfig = await import(configPath + `?timestamp=${new Date().getTime()}`).then(module => module.default);
} catch (error) {
console.error(`Failed to load config from ${configPath}`, error);
}
Expand All @@ -24,10 +24,8 @@ const loadUserConfig = async () => {
};

export default defineConfig(async () => {
const outputDir = process.env.OUTPUT_DIR || path.resolve(__dirname, 'dist'); // 开发模式下输出到 navpress 包的 dist 目录
const userConfig = await loadUserConfig();

// 修改为使用 navpress 包内的 index.html
const outputDir = process.env.OUTPUT_DIR || path.resolve(__dirname, 'dist');
let userConfig = await loadUserConfig();
const indexHtmlPath = path.resolve(__dirname, 'index.html');
const basePath = userConfig.base || '/';

Expand All @@ -46,12 +44,32 @@ export default defineConfig(async () => {
.replace(/<meta name="author" content=".*">/, `<meta name="author" content="${userConfig.meta?.author || ''}">`);
},
},
{
name: 'watch-external',
configureServer(server) {
const configPath = process.env.CONFIG_PATH || path.resolve(process.cwd(), 'navpress.config.js');
server.watcher.add(configPath);
server.watcher.on('change', async (file) => {
if (file === configPath) {
userConfig = await loadUserConfig();
// 更新 define 配置中的 __USER_CONFIG__
server.config.define['__USER_CONFIG__'] = JSON.stringify(userConfig);
server.ws.send({
type: 'custom',
event: 'config-updated',
data: userConfig,
});
console.log(`Config file changed: ${configPath}. Reload`);
}
});
}
}
],
css: {
postcss: {
plugins: [
tailwindcss({
config: path.resolve(__dirname, 'tailwind.config.js'), // 明确指向 `tailwind.config.js` 的路径
config: path.resolve(__dirname, 'tailwind.config.js'),
}),
autoprefixer,
],
Expand All @@ -60,15 +78,19 @@ export default defineConfig(async () => {
define: {
__USER_CONFIG__: JSON.stringify(userConfig),
},
root: path.resolve(__dirname, ''), // 开发模式下使用 navpress 包的目录
root: path.resolve(__dirname),
build: {
outDir: outputDir,
rollupOptions: {
input: indexHtmlPath, // 指向 `navpress` 源代码中的 `index.html`
input: indexHtmlPath,
},
},
server: {
open: true, // 自动在浏览器中打开
open: true,
watch: {
usePolling: true,
interval: 300,
},
},
};
});

0 comments on commit 0632851

Please sign in to comment.