使用Webpack 2

时间:2016-12-21 15:39:59

标签: javascript angularjs highcharts webpack webpack-2

我在角项目中使用以下包:

https://github.com/pablojim/highcharts-ng

一个要求是它需要highcharts作为全局依赖,它告诉你在你的html中添加一个脚本标记:

<script src="http://code.highcharts.com/highcharts.src.js"></script>

不是将上面的脚本标记添加到我的HTML中,而是希望通过Webpack将其设置为全局。

我已经通过npm安装了highcharts,并尝试使用此处描述的ProvidePlugin和noParse方法(无济于事):https://webpack.js.org/guides/shimming/#scripts-loader

对于我使用的ProvidePlugin选项:

new webpack.ProvidePlugin({
  Highcharts: "highcharts",
})

for noParse:

noParse: [
  /[\/\\]node_modules[\/\\]highcharts[\/\\]highcharts\.js$/,
],

两者都没有用,这意味着当highcharts-ng尝试工作时,它会出错,因为它无法创建new Highcharts

TypeError: Cannot read property 'Chart' of undefined

// from highcharts-ng which throws above error
chart = new Highcharts[chartType](mergedOptions, func);

这是我的角度模块

import angular from 'angular'
import highchartsNg from 'highcharts-ng'
import { ReportsData } from './reports.data'
import { reportsWidget } from './reports-widget/component'

export const ReportsModule = angular
  .module('reports', [
    highchartsNg,
  ])
  .factory('ReportsData', ReportsData)
  .component('reportsWidget', reportsWidget)
  .name

我的webpack配置:

var webpack = require('webpack')

module.exports = {
  context: __dirname + '/app/modules',
  entry: {
    vendor: ['angular', 'highcharts-ng'],
    modules: './modules.js',
  },
  output: {
    path: __dirname + '/.tmp/modules',
    filename: '[name].bundle.js',
  },
  plugins: [
    // info: https://webpack.js.org/guides/code-splitting-libraries/
    new webpack.optimize.CommonsChunkPlugin({
      name: ['vendor', 'manifest'],
    }),
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: { presets: ['es2015'] },
          },
        ],
      },
    ],
  },
}

1 个答案:

答案 0 :(得分:0)

在第一次使用require('expose-loader?Highcharts!highcharts');全局变量之前,使用expose-loader并在某处写Highcharts。这将需要highcharts并保存在浏览器中将其公开为window.Highcharts

在引擎盖下,webpack可以为您提供:

/* 0 */
/***/ function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {module.exports = global["Highcharts"] = __webpack_require__(1);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))

/***/ }