How can I set $window.variable using webpack?

时间:2017-06-15 10:02:42

标签: angularjs webpack

I'm migrating a project from a custom builder using Grunt to Webpack and I'm having a problem importing an external library.

This library I have to import is named angular-hu-caches and requires $window.LRUCache to exist (https://github.com/angular-hu/bower-caches/blob/master/caches.js#L414)

I've configured my ProvidePlugin like this but it is not working:

  plugins: [
    new webpack.ProvidePlugin({
      'UNIAPI.Types': 'uniapi-types',
      'window.UAParser': 'ua-parser',
      'window.LRUCache': 'serialized-lru-cache',
      'LRUCache': 'serialized-lru-cache'
    })
 ],

Aliases are configured like this:

resolve: {
  alias: {
    // ...
    'serialized-lru-cache': 'serialized-lru-cache/lib/lru-cache.js'
  }
}

I think the problem is using $window instead of window. What can I do?

2 个答案:

答案 0 :(得分:1)

You should try DefinePlugin, something like this:

plugins: [
  new webpack.DefinePlugin({
    'UNIAPI.Types': 'uniapi-types',
    UAParser: 'ua-parser',
    LRUCache: 'serialized-lru-cache'
  })
],

答案 1 :(得分:1)

我尝试了@serginator解决方案,但它没有正常工作,因为导入的库使用$ window.LRUCache来引用LRUCache而不是window.LRUCache。

我终于使用expose-loader

解决了这个问题
// I require LRUCache once before loading the lib.
require("expose-loader?LRUCache!serialized-lru-cache");

// I use an alias in webpack.config.js
'serialized-lru-cache': 'serialized-lru-cache/lib/lru-cache.js',

该代码在窗口中将LRUCache公开为全局对象并解决了问题。