npm.io
1.0.1 • Published yesterday

@bridgerb/port-from-name

Licence
Unlicense
Version
1.0.1
Deps
0
Size
9 kB
Vulns
0
Weekly
0

@bridgerb/port-from-name

Give every project its own dev-server port, automatically. The port comes from your project's name, so it's the same every time you run it — no more "port 5173 is already in use" when you've got a couple of apps going at once.

Install

npm install -D @bridgerb/port-from-name

Use it

Add it to vite.config.ts and you're done:

import { sveltekit } from '@sveltejs/kit/vite';
import { autoPort } from '@bridgerb/port-from-name';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [sveltekit(), autoPort()],
});

It picks a stable port for both npm run dev and npm run preview. If two apps ever happen to pick the same one, Vite just bumps to the next free port instead of crashing.

What ports it uses

By default it picks from 3100–4899. That range is chosen to stay out of the way:

  • Above the low ports your OS reserves (anything under 1024).
  • Past the usual suspects everything else grabs — 3000 (Node/Next/Rails), 5173 (Vite's default), 5432 (Postgres), and 5000/7000 (AirPlay on Mac).
  • Well below the high ports your machine hands out for its own connections, so you're never fighting it for one.

It's also wide enough that running a handful of apps at once almost never picks the same port twice. Want a different range? Set base and range (see below).

Just want the number?

import { portFromName } from '@bridgerb/port-from-name';

const port = portFromName();              // from this project's name
const port2 = portFromName({ name: 'my-app' });

Options

autoPort({
  name,        // use a custom name instead of package.json's
  base,        // lowest port to pick (default 3100)
  range,       // how wide the range is (default 1800, so 3100–4899)
  strictPort,  // crash instead of bumping on a clash (default false)
});

License

Unlicense — public domain.

Keywords