Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'global' undefined after running webpack

Tags:

webpack

I have a very simple wrapper module around a global object set by the environment the scripts are run. The wrapper module simply does:

module.exports = global.foobar;

Previously when I used browserify this worked fine. When in the browser, global was the same as window.

However, I'm switching to webpack and after running webpack the meaning of global has changed. In the browser it's no longer an alias to window, instead it's undefined, and I get cannot read property foobar of undefined.

Now, in the case of my wrapper module I can fix that in other ways, but I have other dependencies, and further down the chain the buffer package is used. That package also uses global (see here) and also crashes after I've run webpack:

Uncaught TypeError: Cannot read property 'TYPED_ARRAY_SUPPORT' of undefined

Is there some way I can make webpack treat global the same way browserify did, with global being an alias of window?

like image 868
Martin Avatar asked Feb 08 '23 00:02

Martin


2 Answers

I finally found the problem. I have two webpack builds: the first one building my library and the second building the demo. The problem was that both configs had:

{
  node: {
    global: true
  }
}

It works fine if the first one (the one building the lib) has global: false, and the second one has global: true.

like image 59
Martin Avatar answered Mar 04 '23 22:03

Martin


add the following plugins in web.config.js file

 plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    {
      'apply': function(compiler) {
        compiler.parser.plugin('expression global', function() {
          this.state.module.addVariable('global', "(function() { return this; }()) || Function('return this')()");
          return true;
        });
      }
    }
  ]
like image 21
Bhagawan Aghade Avatar answered Mar 04 '23 23:03

Bhagawan Aghade