Skip to content

Commit

Permalink
Format dev-tools and webpack folder
Browse files Browse the repository at this point in the history
  • Loading branch information
the1812 committed Oct 12, 2022
1 parent 92314ce commit e6e2ccd
Show file tree
Hide file tree
Showing 23 changed files with 275 additions and 302 deletions.
1 change: 0 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ typings/
dist/
dev/
node_modules/
*.config.*
.eslintrc.*
14 changes: 6 additions & 8 deletions dev-tools/dev-server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ interface DevServerConfig {
port?: number
maxWatchers?: number
}
const configFile = (path: string) => () => (
existsSync(path)
? JSON.parse(readFileSync(path, { encoding: 'utf-8' }))
: {}
)
const configFile = (path: string) => () =>
existsSync(path) ? JSON.parse(readFileSync(path, { encoding: 'utf-8' })) : {}
const configSource: (() => DevServerConfig)[] = [
() => ({
port: 23333,
maxWatchers: 16,
}),
configFile('dev/dev-server.json'),
]
export const devServerConfig = configSource.reduce((previous, current) => (
{ ...previous, ...current() }
), {} as DevServerConfig)
export const devServerConfig = configSource.reduce(
(previous, current) => ({ ...previous, ...current() }),
{} as DevServerConfig,
)
40 changes: 23 additions & 17 deletions dev-tools/dev-server/core-watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,26 @@ import webpackConfig from '../../webpack/webpack.dev'
import { sendMessage } from './web-socket-server'
import { defaultWatcherHandler } from './watcher-common'

export const startCoreWatcher = () => new Promise<void>(resolve => {
const compiler = webpack(webpackConfig as webpack.Configuration)
console.log('本体编译中...')
const instance = compiler.watch({}, defaultWatcherHandler(
() => resolve(),
result => {
console.log('本体已编译:', result.hash)
sendMessage({
type: 'coreUpdate',
})
},
))
exitHook(exit => instance.close(() => {
console.log('本体编译器已退出')
exit()
}))
})
export const startCoreWatcher = () =>
new Promise<void>(resolve => {
const compiler = webpack(webpackConfig as webpack.Configuration)
console.log('本体编译中...')
const instance = compiler.watch(
{},
defaultWatcherHandler(
() => resolve(),
result => {
console.log('本体已编译:', result.hash)
sendMessage({
type: 'coreUpdate',
})
},
),
)
exitHook(exit =>
instance.close(() => {
console.log('本体编译器已退出')
exit()
}),
)
})
17 changes: 8 additions & 9 deletions dev-tools/dev-server/payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ export type QuerySessionsResponsePayload = PayloadBase<'querySessionsResponse'>
}
export type StopPayload = PayloadBase<'stop'>

export type Payload = (
StartPayload |
CoreUpdatePayload |
ItemUpdatePayload |
StopPayload |
ItemStopPayload |
QuerySessionsPayload |
QuerySessionsResponsePayload
)
export type Payload =
| StartPayload
| CoreUpdatePayload
| ItemUpdatePayload
| StopPayload
| ItemStopPayload
| QuerySessionsPayload
| QuerySessionsResponsePayload

export type MessageHandler<P extends Payload = Payload> = (payload: P) => void
40 changes: 22 additions & 18 deletions dev-tools/dev-server/registry-watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,27 @@ export const stopInstance = (instance: Watching, onClose: () => void) => {
}
}

export const startRegistryWatcher = (url: string, config: Configuration) => new Promise<void>(
resolve => {
export const startRegistryWatcher = (url: string, config: Configuration) =>
new Promise<void>(resolve => {
console.log(`功能编译中... ${url}`)
const { maxWatchers } = devServerConfig
const watcher = webpack(config)
const instance = watcher.watch({}, defaultWatcherHandler(
() => {
resolve()
},
result => {
console.log('功能已编译:', result.hash, url)
sendMessage({
type: 'itemUpdate',
path: url,
sessions: watchers.map(it => it.url),
})
},
))
const instance = watcher.watch(
{},
defaultWatcherHandler(
() => {
resolve()
},
result => {
console.log('功能已编译:', result.hash, url)
sendMessage({
type: 'itemUpdate',
path: url,
sessions: watchers.map(it => it.url),
})
},
),
)
exitHook(exit => {
if (!instance.closed) {
instance.close(() => {
Expand All @@ -63,9 +66,10 @@ export const startRegistryWatcher = (url: string, config: Configuration) => new
if (watchers.length >= maxWatchers) {
const oldInstance = watchers.shift()
stopInstance(oldInstance.instance, () => {
console.log(`已达到 maxWatchers 数量 (${maxWatchers}), 退出了功能编译器: ${oldInstance.url}`)
console.log(
`已达到 maxWatchers 数量 (${maxWatchers}), 退出了功能编译器: ${oldInstance.url}`,
)
})
}
watchers.push({ url, instance })
},
)
})
91 changes: 44 additions & 47 deletions dev-tools/dev-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,54 @@ import { buildByEntry } from '../../registry/webpack/config'
import { exitWebSocketServer } from './web-socket-server'
import { watchers, parseRegistryUrl, startRegistryWatcher } from './registry-watcher'

export const startDevServer = () => new Promise<Server>(resolve => {
const { port } = devServerConfig
export const startDevServer = () =>
new Promise<Server>(resolve => {
const { port } = devServerConfig

const server = createServer((request, response) => {
const { url } = request
console.log('请求:', url)
const callHandler = () => {
handler(request, response, {
public: '.',
directoryListing: [
'/dist',
'/dist/**',
'/registry/dist',
'/registry/dist/**',
],
})
}
if (url.startsWith('/registry')) {
const existingWatcher = watchers.find(w => w.url === url)
const registryInfo = parseRegistryUrl(url)
if (existingWatcher && registryInfo) {
console.log(`已复用功能编译器: ${url}`)
const server = createServer((request, response) => {
const { url } = request
console.log('请求:', url)
const callHandler = () => {
handler(request, response, {
public: '.',
directoryListing: ['/dist', '/dist/**', '/registry/dist', '/registry/dist/**'],
})
}
if (existingWatcher || !registryInfo) {
callHandler()
if (url.startsWith('/registry')) {
const existingWatcher = watchers.find(w => w.url === url)
const registryInfo = parseRegistryUrl(url)
if (existingWatcher && registryInfo) {
console.log(`已复用功能编译器: ${url}`)
}
if (existingWatcher || !registryInfo) {
callHandler()
} else {
startRegistryWatcher(
url,
buildByEntry({
...registryInfo,
mode: 'development',
}) as Configuration,
).then(() => callHandler())
}
} else {
startRegistryWatcher(url, buildByEntry({
...registryInfo,
mode: 'development',
}) as Configuration).then(
() => callHandler(),
)
callHandler()
}
} else {
callHandler()
}
})
exitHook(exit => {
exitWebSocketServer()
server.close(error => {
if (error) {
console.error(error)
})
exitHook(exit => {
exitWebSocketServer()
server.close(error => {
if (error) {
console.error(error)
exit()
return
}
console.log('DevServer 已退出')
exit()
return
}
console.log('DevServer 已退出')
exit()
})
})
server.listen(port, () => {
console.log(`DevServer 已启动, 端口: ${port}`)
resolve(server)
})
})
server.listen(port, () => {
console.log(`DevServer 已启动, 端口: ${port}`)
resolve(server)
})
})
16 changes: 9 additions & 7 deletions dev-tools/dev-server/watcher-common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ export const defaultWatcherHandler = (
}
const needLogging = result.hasErrors() || result.hasWarnings()
if (needLogging) {
console.log(result.toString({
hash: false,
assets: false,
modules: false,
chunks: false,
color: true,
}))
console.log(
result.toString({
hash: false,
assets: false,
modules: false,
chunks: false,
color: true,
}),
)
}
if (result.hasErrors()) {
lastHash = ''
Expand Down
77 changes: 40 additions & 37 deletions dev-tools/dev-server/web-socket-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,45 +22,48 @@ export const exitWebSocketServer = () => {
sendMessage({ type: 'stop' })
server.clients.forEach(c => c.close())
}
export const startWebSocketServer = (httpServer: Server) => new Promise<void>(resolve => {
server = new WebSocketServer({ server: httpServer })
server.on('connection', client => {
sendMessage({ type: 'start', sessions: watchers.map(it => it.url) })
client.on('message', data => {
try {
const payload: Payload = JSON.parse(data.toString())
console.log('收到 DevClient 消息:', payload)
switch (payload.type) {
default: {
break
}
case 'itemStop': {
const { path } = payload
const watcherIndex = watchers.findIndex(it => it.url === path)
if (watcherIndex !== -1) {
const [watcher] = watchers.splice(watcherIndex, 1)
stopInstance(watcher.instance, () => {
console.log(`功能编译器已退出: ${watcher.url}`)
})
export const startWebSocketServer = (httpServer: Server) =>
new Promise<void>(resolve => {
server = new WebSocketServer({ server: httpServer })
server.on('connection', client => {
sendMessage({ type: 'start', sessions: watchers.map(it => it.url) })
client.on('message', data => {
try {
const payload: Payload = JSON.parse(data.toString())
console.log('收到 DevClient 消息:', payload)
switch (payload.type) {
default: {
break
}
case 'itemStop': {
const { path } = payload
const watcherIndex = watchers.findIndex(it => it.url === path)
if (watcherIndex !== -1) {
const [watcher] = watchers.splice(watcherIndex, 1)
stopInstance(watcher.instance, () => {
console.log(`功能编译器已退出: ${watcher.url}`)
})
}
break
}
case 'querySessions': {
sendMessage({ type: 'querySessionsResponse', sessions: watchers.map(it => it.url) })
break
}
break
}
case 'querySessions': {
sendMessage({ type: 'querySessionsResponse', sessions: watchers.map(it => it.url) })
break
}
} catch (error) {
console.error('无效信息', data)
}
} catch (error) {
console.error('无效信息', data)
}
})
})
server.on('error', error => console.error(error))
exitHook(exit =>
server.close(error => {
if (error) {
console.error(error)
}
exit()
}),
)
resolve()
})
server.on('error', error => console.error(error))
exitHook(exit => server.close(error => {
if (error) {
console.error(error)
}
exit()
}))
resolve()
})
Loading

0 comments on commit e6e2ccd

Please sign in to comment.