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

This commit is contained in:
John Rees 2021-06-28 21:31:41 +01:00 committed by GitHub
parent c7de475177
commit a7f6af2cc6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 9 deletions

View File

@ -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
ts/src/utils/common.ts Normal file
View File

@ -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");

View File

@ -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");