Awadhoot
Awadhoot

Reputation: 747

function exported into global scope is undefined (webpack + babel)

I have three separate libraries -

  1. Lib A - Hosts shared code and uses babel to transpile the code into a /lib folder
  2. Lib B - which uses libA (imports the babel transpiled code) and it uses webpack to generate the bundle in a dist folder (dist/index.js). It also exports a global function "myGlobalFunction" by attaching it to a window.
  3. Lib C - Uses both A and the global "myGlobalFunction".

Issue is, the window.myGlobalFunction when accessed from lib C, prints undefined.

In Library B, if I import the contents of Lib A from src/ instead of the transpiled lib/, my issue gets resolved automatically.

Not sure why this is happening. Also, I have disabled the es modules transpilation in babel by setting

{modules: false} 

in babelrc of the libA.

I have a problem similar to this one but the solution posted there didnt work either as I need to use the global in some another library by directly looking in the Window object.

All the libraries are separate npm packages.

Upvotes: 0

Views: 239

Answers (1)

Awadhoot
Awadhoot

Reputation: 747

I figured out the issue being how babel was transpiling the code from LibA - especially the code including async...await.

It uses the preset env and fb's regenerator runtime to transpile async..await into Promises using generators.

I disabled the "transform-regenerator", "transform-async-to-generator" plugins and used fast-async plugin to do the job and my issue was resolved.

Another way is to use the babel's transform runtime plugin which also solved my issue.

I suspect the main issue was the code which uses regeneratorRuntime was not being resolved, not sure about that, but the workaround solved my problem.

Upvotes: 0

Related Questions