Skip to content

Commit

Permalink
feat(status): optimize build flow
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Mar 30, 2021
1 parent e7e28cb commit d626a14
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 83 deletions.
89 changes: 43 additions & 46 deletions packages/plugin-status/build/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/* eslint-disable quote-props */

import { build } from 'vite'
import * as vite from 'vite'
import { resolve } from 'path'
import { copyFile } from 'fs-extra'
import createPluginVue from '@vitejs/plugin-vue'

const root = resolve(__dirname, '../client')
const pkgRoot = resolve(__dirname, '..')
const dist = resolve(__dirname, '../dist')
const pluginVue = createPluginVue()

function findModulePath(id: string) {
Expand All @@ -15,79 +15,76 @@ function findModulePath(id: string) {
return path.slice(0, path.indexOf(keyword)) + keyword.slice(0, -1)
}

;(async () => {
// build for index.html
await build({
function build(root: string, config: vite.UserConfig) {
const { rollupOptions } = config.build || {}
return vite.build({
...config,
root,
base: './',
build: {
outDir: '../dist',
minify: 'esbuild',
emptyOutDir: true,
...config.build,
rollupOptions: {
external: ['./~/vue', './~/client'],
...rollupOptions,
external: [root + '/vue.js', root + '/vue-router.js', root + '/client.js'],
output: rollupOptions?.input ? {
format: 'module',
entryFileNames: '[name].js',
...rollupOptions.output,
} : undefined,
},
},
resolve: {
alias: {
'vue': root + '/vue.js',
'vue-router': root + '/vue-router.js',
'~/client': root + '/client.js',
...config.resolve?.alias,
},
},
})
}

;(async () => {
// build for index.html
await build(root, {
base: './',
plugins: [pluginVue],
resolve: {
alias: {
'vue': './~/vue',
'~/client': './~/client',
'~/variables': root + '/index.scss',
},
},
})

// build for client.js
await build({
root,
await copyFile(findModulePath('vue') + '/dist/vue.runtime.esm-browser.prod.js', dist + '/vue.js')

// build for client.js, vue-router.js
await build(resolve(__dirname, '../../..'), {
build: {
outDir: '../dist/~',
minify: 'esbuild',
lib: {
formats: ['es'],
entry: 'index.ts',
name: 'KoishiClient',
},
outDir: dist,
emptyOutDir: false,
rollupOptions: {
external: ['./~/vue', './~/client'],
output: {
entryFileNames: 'client.js',
input: {
'client': root + '/index.ts',
'vue-router': findModulePath('vue-router') + '/dist/vue-router.esm-browser.js',
},
},
},
resolve: {
alias: {
'vue': './~/vue',
'~/client': './~/client',
treeshake: false,
preserveEntrySignatures: 'strict',
},
},
})

await copyFile(findModulePath('vue') + '/dist/vue.runtime.esm-browser.prod.js', pkgRoot + '/dist/~/vue.js')

// build for koishi-plugin-teach
build({
const teach = resolve(__dirname, '../../plugin-teach/client')
build(teach, {
build: {
minify: 'esbuild',
emptyOutDir: true,
assetsDir: '',
outDir: resolve(__dirname, '../../plugin-teach/dist'),
rollupOptions: {
input: resolve(__dirname, '../../plugin-teach/client'),
external: ['./~/client', './~/vue'],
output: {
format: 'es',
entryFileNames: '[name].js',
},
input: teach + '/index.ts',
},
},
plugins: [pluginVue],
resolve: {
alias: {
'vue': './~/vue',
'koishi-plugin-status/client': './~/client',
},
},
})
})()
13 changes: 0 additions & 13 deletions packages/plugin-status/client/index.dev.html

This file was deleted.

3 changes: 0 additions & 3 deletions packages/plugin-status/client/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
<link rel="icon" href="./assets/koishi.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Koishi 控制台</title>
<script src="./assets/vue.runtime.global.prod.js"></script>
<script src="./assets/vue-router.global.prod.js"></script>
<script src="./assets/koishi-client.js"></script>
</head>
<body>
<div id="app"></div>
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-status/client/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Button from './components/button.vue'
import Input from './components/input.vue'
import Numeric from './components/numeric.vue'
import App from './views/layout/index.vue'
import { start, user, receive, router } from '.'
import { start, user, receive, router } from '~/client'

import '@fortawesome/fontawesome-free/css/fontawesome.css'
import '@fortawesome/fontawesome-free/css/brands.css'
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-status/client/views/layout/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</template>
<main :class="{ frameless }">
<router-view v-if="loaded"/>
<p v-else>正在加载数据……</p>
</main>
</template>

Expand Down
1 change: 1 addition & 0 deletions packages/plugin-status/server/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ export class Meta implements DataSource<Meta.Payload> {
}

extend(callback: Meta.Extension) {
this.timestamp = 0
this.callbacks.push(callback)
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-status/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export function apply(ctx: Context, config: Config = {}) {
session.user.lastCall = new Date()
})

ctx.router?.get(apiPath, async (koa) => {
ctx.router.get(apiPath, async (koa) => {
koa.set('Access-Control-Allow-Origin', '*')
koa.body = await getStatus()
})
Expand Down
29 changes: 12 additions & 17 deletions packages/plugin-status/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,30 +54,27 @@ export class WebServer {
const { uiPath } = this.config
const [vite] = await Promise.all([this.createVite(), this.createAdapter()])

this.ctx.router.get(uiPath + '/plugin/:name', async (ctx) => {
const filename = this.entries[ctx.params.name]
if (!filename) return ctx.status = 404
ctx.type = extname(filename)
return ctx.body = createReadStream(filename)
})

this.ctx.router.get(uiPath + '(/.+)*', async (ctx) => {
// add trailing slash and redirect
if (ctx.path === uiPath && !uiPath.endsWith('/')) {
return ctx.redirect(ctx.path + '/')
}
const filename = resolve(this.root, ctx.path.slice(uiPath.length).replace(/^\/+/, ''))
const name = ctx.path.slice(uiPath.length).replace(/^\/+/, '')
const sendFile = (filename: string) => {
ctx.type = extname(filename)
return ctx.body = createReadStream(filename)
}
if (this.entries[name]) return sendFile(this.entries[name])
const filename = resolve(this.root, name)
if (!filename.startsWith(this.root) && !filename.includes('node_modules')) {
return ctx.status = 403
}
const stats = await fs.stat(filename).catch<Stats>(noop)
if (stats?.isFile()) {
ctx.type = extname(filename)
return ctx.body = createReadStream(filename)
}
let template = await fs.readFile(resolve(this.root, `index.${this.config.devMode ? 'dev.' : ''}html`), 'utf8')
if (stats?.isFile()) return sendFile(filename)
console.log(ctx.path, stats)
let template = await fs.readFile(resolve(this.root, 'index.html'), 'utf8')
if (vite) template = await vite.transformIndexHtml(uiPath, template)
ctx.set('content-type', 'text/html')
ctx.type = 'html'
ctx.body = this.transformHtml(template)
})
}
Expand All @@ -87,9 +84,7 @@ export class WebServer {
return `window.KOISHI_${snakeCase(key).toUpperCase()} = ${JSON.stringify(value)};`
}).join('\n') + '</script>'
const bodyInjection = Object.entries(this.entries).map(([name, filename]) => {
const src = this.config.devMode
? '/vite/@fs' + filename
: this.config.uiPath + '/~/' + name
const src = this.config.devMode ? '/vite/@fs' + filename : `./${name}`
return `<script type="module" src="${src}"></script>`
}).join('\n')
return template
Expand Down
4 changes: 2 additions & 2 deletions packages/plugin-teach/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,10 @@ export function apply(ctx: Context, config: Config = {}) {
})

const filename = resolve(__dirname, webui.config.devMode ? '../client' : '../dist/index.js')
webui.entries.teach = filename
webui.entries['teach.js'] = filename

ctx.before('disconnect', () => {
delete webui.entries.teach
delete webui.entries['teach.js']
})
}
}

0 comments on commit d626a14

Please sign in to comment.