Манипулировать глобальным объемом импортируемого файла - PullRequest
0 голосов
/ 01 октября 2019

Интересно, как манипулировать глобальной областью импортируемого файла для какого-либо объекта. Например, импортированный файл:

// File A.js
export const str = `hello ${world}`;

function export foo() {
 return n1 + n2;
}

Затем я хочу использовать объект для глобальной области импортируемого файла, например:

const scope1 = {
  world: 'world',
  n1: 1,
  n2: 2
}

const scope2 = {
  world: 'to you',
  n1: 100,
  n2: 200
}

Затем, когда я импортирую import * as A from 'A',глобальная область будет взята из объектов scope1 или scope2 (например, bind, но для оператора import).

Существует ли простой способ добиться такого поведения?

1 Ответ

0 голосов
/ 01 октября 2019

Вы можете экспортировать строку шаблона в виде строки, затем в файле, в который вы импортируете, вы можете выполнить return new Function("return "+ templateString +" ;").call(templateVars);, который оценит ваше выражение ( образец ):

//A.ts
export const str = "hello ${this.world}";

export function foo() {
  return this.n1 + this.n2;
}
//index.ts
import * as A from "./A";

class Scope {
  n1: number;
  n2: number;
  _world: string;

  get world(): string {
    return this.getValue(this._world);
  }

  set world(newWorld) {
    this._world = newWorld;
  }

  constructor({ n1, n2, world }) {
    this.n1 = n1;
    this.n2 = n2;
    this._world = world;
  }

  getValue(accessVariable) {
    return new Function("return `" + accessVariable + "`;").bind(this).call();
  }

  getResult(fn: Function) {
    return fn.bind(this).call();
  }
}

const scope1 = new Scope({ world: "world", n1: 1, n2: 2 });
const scope2 = new Scope({ world: "to you", n1: 100, n2: 200 });
console.log(scope1.getValue(A.str), scope2.getValue(A.str));
//output: hello world hello to you
console.log(scope1.getResult(A.foo), scope2.getResult(A.foo));
//output: 3 300
...