Skip to content

Commit

Permalink
feat: auto detect port
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyinws committed Jan 30, 2024
1 parent 03c2eb4 commit 295e586
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 28 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@
"dependencies": {
"@rollup/pluginutils": "^5.1.0",
"ast-kit": "^0.11.3",
"get-port-please": "^3.1.2",
"h3": "^1.10.0",
"launch-editor": "^2.6.1",
"magic-string": "^0.30.5",
Expand Down
52 changes: 29 additions & 23 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 22 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { UnpluginFactory } from 'unplugin'
import { createUnplugin } from 'unplugin'
import { checkPort, getRandomPort } from 'get-port-please'
import type { Context, Options } from './types'
import { DETAULT_OPTIONS, PLUGIN_NAME } from './core/constants'
import { startServer } from './core/server/index'
Expand All @@ -11,6 +12,13 @@ export const unpluginFactory: UnpluginFactory<Options | undefined> = (options =
...DETAULT_OPTIONS,
...options,
}

async function detectPort() {
const isAvailable = await checkPort(mergedOptions.port!)
if (!isAvailable)
mergedOptions.port = await getRandomPort()
}

return {
name: PLUGIN_NAME,
enforce: getEnforce[meta.framework] || 'post',
Expand All @@ -32,31 +40,40 @@ export const unpluginFactory: UnpluginFactory<Options | undefined> = (options =
},
vite: {
apply: 'serve',
configureServer() {
async configureServer() {
if (options.disableLaunchEditor)
return

await detectPort()

startServer(mergedOptions.port)
},
},
webpack(compiler) {
async webpack(compiler) {
if (options.disableLaunchEditor)
return

await detectPort()

if (compiler.options.mode === 'development') {
compiler.hooks.done.tap(PLUGIN_NAME, async (state) => {
compiler.hooks.done.tap(PLUGIN_NAME, (state) => {
if (state.hasErrors())
return
startServer(mergedOptions.port)
})
}
},
rspack(compiler) {
async rspack(compiler) {
if (options.disableLaunchEditor)
return

await detectPort()

if (compiler.options.mode === 'development') {
compiler.hooks.done.tap(PLUGIN_NAME, async (state) => {
compiler.hooks.done.tap(PLUGIN_NAME, (state) => {
if (state.hasErrors())
return

startServer(mergedOptions.port)
})
}
Expand Down

0 comments on commit 295e586

Please sign in to comment.