5

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?

Martin
  • 8,876
  • 2
  • 35
  • 36

3 Answers3

7

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.

Martin
  • 8,876
  • 2
  • 35
  • 36
  • You could remove the second `global:true` as the default is true. – Raathigesh Apr 22 '16 at 07:28
  • 1
    It works for me. After I enabled the `pause on exceptions` option in chrome console, I found the `global` is `undefined`. This solution helped me to solve this problem. – Max Peng Nov 14 '16 at 14:46
1

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;
        });
      }
    }
  ]
0

defined webpackConfig and add

plugins: [new webpack.DefinePlugin({
    global: {}
})],
Draken
  • 3,134
  • 13
  • 34
  • 54
戈晓伟
  • 181
  • 1
  • 3