Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid assigning globalThis.process when not defined. #94

Merged
merged 2 commits into from
Mar 17, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 10 additions & 12 deletions packages/ts-invariant/src/invariant.ts
Original file line number Diff line number Diff line change
@@ -61,18 +61,16 @@ export function setVerbosity(level: VerbosityLevel): VerbosityLevel {
// import this process stub to avoid errors evaluating process.env.NODE_ENV.
// However, because most ESM-to-CJS compilers will rewrite the process import
// as tsInvariant.process, which prevents proper replacement by minifiers, we
// also attempt to define the stub globally when it is not already defined.
const processStub = global.process || { env: {} };
// also export processStub, so you can import { invariant, processStub } from
// "ts-invariant" and assign processStub to a local variable named process.
export const processStub: {
env: Record<string, any>;
[key: string]: any;
} = (
typeof process === "object" &&
typeof process.env === "object"
) ? process : { env: {} };

export { processStub as process };
if (!global.process) try {
Object.defineProperty(globalThis, "process", {
value: processStub,
writable: true,
enumerable: false,
configurable: true
});
} catch {
// If this fails, it isn't the end of the world.
}

export default invariant;
12 changes: 11 additions & 1 deletion packages/ts-invariant/src/tests.ts
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import defaultExport, {
InvariantError,
setVerbosity,
process,
processStub,
} from "./invariant";
import reactInvariant from "invariant";

@@ -144,7 +145,16 @@ describe("ts-invariant", function () {
checkConsoleMethod("error", true);
});

it("should provide a usable process.env stub", function () {
it("should export a usable process polyfill", function () {
assert.strictEqual(typeof process, "object");
assert.strictEqual(typeof process.env, "object");
if (process.versions) {
assert.strictEqual(typeof process.versions.node, "string");
}
});

it("should export a usable processStub", function () {
const process = processStub;
assert.strictEqual(typeof process, "object");
assert.strictEqual(typeof process.env, "object");
if (process.versions) {