Skip to content

Commit

Permalink
Feature: pick PORT number also from .env file (#7819)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinyaigeek committed Mar 18, 2022
1 parent fe51929 commit 7b16851
Showing 1 changed file with 47 additions and 10 deletions.
57 changes: 47 additions & 10 deletions packages/core/core/src/resolveOptions.js
Expand Up @@ -4,6 +4,7 @@ import type {
FilePath,
InitialParcelOptions,
DependencySpecifier,
InitialServerOptions,
} from '@parcel/types';
import type {FileSystem} from '@parcel/fs';
import type {ParcelOptions} from './types';
Expand Down Expand Up @@ -95,6 +96,19 @@ export default async function resolveOptions(
throw new Error('Lazy bundling does not work with content hashing');
}

let env = {
...(await loadDotEnv(
initialOptions.env ?? {},
inputFS,
path.join(projectRoot, 'index'),
projectRoot,
)),
...process.env,
...initialOptions.env,
};

let port = determinePort(initialOptions.serveOptions, env.PORT);

return {
config: getRelativeConfigSpecifier(
inputFS,
Expand All @@ -107,16 +121,7 @@ export default async function resolveOptions(
initialOptions.defaultConfig,
),
shouldPatchConsole: initialOptions.shouldPatchConsole ?? false,
env: {
...(await loadDotEnv(
initialOptions.env ?? {},
inputFS,
path.join(projectRoot, 'index'),
projectRoot,
)),
...process.env,
...initialOptions.env,
},
env,
mode,
shouldAutoInstall: initialOptions.shouldAutoInstall ?? false,
hmrOptions: initialOptions.hmrOptions ?? null,
Expand All @@ -126,6 +131,7 @@ export default async function resolveOptions(
? {
...initialOptions.serveOptions,
distDir: distDir ?? path.join(outputCwd, 'dist'),
port,
}
: false,
shouldDisableCache: initialOptions.shouldDisableCache ?? false,
Expand Down Expand Up @@ -178,3 +184,34 @@ function getRelativeConfigSpecifier(
return specifier;
}
}

function determinePort(
initialServerOptions: InitialServerOptions | false | void,
portInEnv: string | void,
defaultPort: number = 1234,
): number {
function parsePort(port: string): number | void {
let parsedPort = Number(port);

// return undefined if port number defined in .env is not valid integer
if (!Number.isInteger(parsedPort)) {
return undefined;
}
return parsedPort;
}

if (!initialServerOptions) {
return typeof portInEnv !== 'undefined'
? parsePort(portInEnv) ?? defaultPort
: defaultPort;
}

// if initialServerOptions.port is equal to defaultPort, then this means that port number is provided via PORT=~~~~ on cli. In this case, we should ignore port number defined in .env.
if (initialServerOptions.port !== defaultPort) {
return initialServerOptions.port;
}

return typeof portInEnv !== 'undefined'
? parsePort(portInEnv) ?? defaultPort
: defaultPort;
}

0 comments on commit 7b16851

Please sign in to comment.