Browse Source

ts: Import node modules if not browser (#436)

John Rees 4 years ago
parent
commit
a7f6af2cc6
3 changed files with 16 additions and 9 deletions
  1. 4 1
      ts/src/provider.ts
  2. 6 0
      ts/src/utils/common.ts
  3. 6 8
      ts/src/workspace.ts

+ 4 - 1
ts/src/provider.ts

@@ -11,6 +11,7 @@ import {
   SimulatedTransactionResponse,
   Commitment,
 } from "@solana/web3.js";
+import { isBrowser } from "./utils/common";
 
 /**
  * The network and wallet context used to send transactions paid for and signed
@@ -54,12 +55,14 @@ export default class Provider {
   }
 
   /**
-   * Returns a `Provider` read from the `ANCHOR_PROVIDER_URL` envirnment
+   * Returns a `Provider` read from the `ANCHOR_PROVIDER_URL` environment
    * variable
    *
    * (This api is for Node only.)
    */
   static env(): Provider {
+    if (isBrowser) return;
+
     const process = require("process");
     const url = process.env.ANCHOR_PROVIDER_URL;
     if (url === undefined) {

+ 6 - 0
ts/src/utils/common.ts

@@ -0,0 +1,6 @@
+/**
+ * Returns true if being run inside a web browser,
+ * false if in a Node process or electron app.
+ */
+export const isBrowser =
+  typeof window !== "undefined" && !window.process?.hasOwnProperty("type");

+ 6 - 8
ts/src/workspace.ts

@@ -3,6 +3,7 @@ import * as toml from "toml";
 import { PublicKey } from "@solana/web3.js";
 import { Program } from "./program";
 import { Idl } from "./idl";
+import { isBrowser } from "./utils/common";
 
 let _populatedWorkspace = false;
 
@@ -15,17 +16,14 @@ let _populatedWorkspace = false;
  */
 const workspace = new Proxy({} as any, {
   get(workspaceCache: { [key: string]: Program }, programName: string) {
-    const fs = require("fs");
-    const process = require("process");
-
-    if (
-      typeof window !== "undefined" &&
-      !window.process?.hasOwnProperty("type")
-    ) {
-      // Workspaces are available in electron, but not in the browser, yet.
+    if (isBrowser) {
+      console.log("Workspaces aren't available in the browser");
       return undefined;
     }
 
+    const fs = require("fs");
+    const process = require("process");
+
     if (!_populatedWorkspace) {
       const path = require("path");