Noitidart
Noitidart

Reputation: 37238

Access modules local scope with `this` and pass it to imported module

I am trying to import a module B into module A. I want to give module B access to all of the local scope in module A.

Before webpack I did it like this:

 var scope = this;

Then I would check for existence of entities like this

if (!('blah' in scope)) {
          throw new Error('method of "' + 'blah' + '" not in scope')
}

I would also be able to set things in module A from module B by doing scope.blah = ....

Is this possible with webpack?

I tried with DefinePlugin and ProvidePlugin, but I can't seem to give module B access to the scope of module A.

Upvotes: 0

Views: 59

Answers (1)

user394010
user394010

Reputation: 374

The module may export one default object and many named items.

It is default module export:

const MyClass = (props) => (
  <div/>
)

export default MyClass

We can import it like this:

import MyClass from "../actions"

The curly braces allows to export named items, so if we have such exports:

const myConst = "The Text"
const myHelper = (num) => 2*num

export default MyClass
export {myHelper, myConst}

We can import its like this:

import MyClass, {myHelper, myConst} from "../actions"

There is not need to add index at path - it is add by default. So write "../actions" enough instead of "../actions/index"

So we can import any exported elements of two modules from each other.

For testing purpose the rewire module helps to bypass export limitations.

EDIT (after comment): I try such code:

# scope.js
var data = ['The data']
var value = 'The value'
var scope = this
var fn = function(){ return scope }
console.log(scope)
export { scope, value, fn }

# index.js
import { scope, fn } from './scope'
console.log(scope)
console.log(scope.data)
console.log(fn())

The result is:

{ a: [Getter], b: [Getter] }
{ a: [Getter], b: [Getter] }
undefined
{ a: [Getter], b: [Getter] }

Where 'a' is scope variable, and 'b' is fn function. So seems package is strongly isolated.

Upvotes: 1

Related Questions