迁移到Webpack / ES6 - 依赖注入失败

时间:2018-01-12 08:49:53

标签: angular webpack dependency-injection ecmascript-6

作为迁移到webpack的一部分,我必须迁移一个库,然后将调用更改为它。我试图对库进行最小的更改,以防止任何向后兼容性问题。这是修改后的库代码:

(function() {

  // only added part to the library
  if (typeof module === 'object' && module.exports) {
    module.exports = mdPickerColors;
  }
  // end of added part

  angular
    .module('mdColorMenu', ['ngAria', 'ngAnimate', 'ngMaterial'])
    .factory('mdPickerColors', ['$mdColorPalette', '$mdPanel', mdPickerColors])
    .directive('mdColorMenu', mdColorMenuDirective);

  function mdPickerColors($mdColorPalette, $mdPanel) {
    //...
  }
  //...
})();

然后在我的代码中,我有一个index.js,如下所示:

import angular from 'angular';

import myService from './myService';

import mdPickerColors from 'md-color-menu';

export default angular.module('myModule', [mdPickerColors])
  .service('myService', myService)
  .name;

最后,myService.js看起来像这样:

import angular from 'angular';

export default function myService(mdPickerColors, /*...*/) {
  //...
}

但是,我收到错误Error: [$injector:unpr] Unknown provider: $mdPanel。然而,第一个依赖项($mdColorPalette)正确注入。

其他信息:

  • 我使用角度版本1.6.4,角度材料版本1.1.4。

  • 当我只是在<script>标记中导入文件时,它会按预期工作。

有什么想法吗?

更新:我注意到我直接出口工厂,而不是模块。这意味着我将工厂声明为模块依赖,这听起来不对。可能是原因吗?

1 个答案:

答案 0 :(得分:0)

我知道这是愚蠢的事。这样:

if (typeof module === 'object' && module.exports) {
  module.exports = mdPickerColors;
}

应替换为:

module.exports = angular.module('mdColorMenu').name;