Skip to content

Commit

Permalink
feat: 运行时获取配置
Browse files Browse the repository at this point in the history
  • Loading branch information
c0dedance committed Oct 14, 2023
1 parent 7a7b3de commit e1c8cff
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 6 deletions.
5 changes: 1 addition & 4 deletions src/node/cli.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { cac } from 'cac'
import { createDevServer } from './dev'
import { build } from './build'

import { version } from '../../package.json'
import { resolveConfig } from './config'

const cli = cac('r-press').version(version).help()

cli
.command('[root]', 'start dev server')
.alias('dev')
.action(async (root: string) => {
await resolveConfig(root, 'serve', 'development')
const server = await createDevServer(root)
await server.listen()
server.printUrls()
Expand All @@ -20,7 +17,7 @@ cli
cli
.command('build [root]', 'build for production')
.action(async (root: string) => {
await resolveConfig(root, 'build', 'production')
// await resolveConfig(root, 'build', 'production')
await build(root)
})

Expand Down
8 changes: 6 additions & 2 deletions src/node/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import { createServer as createViteDevServer } from 'vite'
import pluginReact from '@vitejs/plugin-react'
import { pluginIndexHtml } from './plugin-r-press/indexHtml'
import { ROOT } from './constant'
import { pluginSiteData } from './plugin-r-press/siteData'
import { resolveConfig } from './config'

export async function createDevServer(root: string = process.cwd()) {
const config = await resolveConfig(root, 'serve', 'development')

export function createDevServer(root: string = process.cwd()) {
return createViteDevServer({
root,
plugins: [pluginIndexHtml(), pluginReact()],
plugins: [pluginIndexHtml(), pluginReact(), pluginSiteData(config)],
server: {
fs: {
// 允许为项目根目录的上一级提供服务
Expand Down
21 changes: 21 additions & 0 deletions src/node/plugin-r-press/siteData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Plugin } from 'vite'

const SITE_DATA_ID = 'rpress:site-data'

export function pluginSiteData(config): Plugin {
return {
name: 'r-press:site-data',
resolveId(id) {
if (id === SITE_DATA_ID) {
return '\0' + SITE_DATA_ID
}
},
load(id) {
if (id === '\0' + SITE_DATA_ID) {
return `
export default ${JSON.stringify(config.siteData)}
`
}
},
}
}
3 changes: 3 additions & 0 deletions src/runtime/client-entry.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { createRoot } from 'react-dom/client'
import App from './App'
import siteData from 'rpress:site-data'

console.log(siteData)

function renderInBrowser() {
const containerEl = document.getElementById('root')
Expand Down

0 comments on commit e1c8cff

Please sign in to comment.