Skip to content

Commit

Permalink
Be more defensive against find/replace __DEV__ minifiers.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Jun 17, 2021
1 parent 608784c commit 020fa76
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/utilities/globals/__DEV__.ts → src/utilities/globals/DEV.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import global from "../common/global";
import { maybe } from "../common/maybe";

// To keep string-based find/replace minifiers from messing with __DEV__ inside
// string literals or properties like global.__DEV__, we construct the "__DEV__"
// string in a roundabout way that won't be altered by find/replace strategies.
const __ = "__";
const GLOBAL_KEY = [__, __].join("DEV");

function getDEV() {
try {
return Boolean(__DEV__);
} catch {
Object.defineProperty(global, "__DEV__", {
Object.defineProperty(global, GLOBAL_KEY, {
// In a buildless browser environment, maybe(() => process.env.NODE_ENV)
// evaluates as undefined, so __DEV__ becomes true by default, but can be
// initialized to false instead by a script/module that runs earlier.
Expand All @@ -14,7 +20,9 @@ function getDEV() {
configurable: true,
writable: true,
});
return global.__DEV__;
// Using computed property access rather than global.__DEV__ here prevents
// string-based find/replace strategies from munging this to global.false:
return (global as any)[GLOBAL_KEY];
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/utilities/globals/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Just in case the graphql package switches from process.env.NODE_ENV to
// __DEV__, make sure __DEV__ is polyfilled before importing graphql.
import DEV from "./__DEV__";
import DEV from "./DEV";
export { DEV }

// Import graphql/jsutils/instanceOf safely, working around its unchecked usage
Expand Down

0 comments on commit 020fa76

Please sign in to comment.