Making a node_module global using Webpack 2

533 views Asked by At

I am using the below package on an angular project:

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

A requirement is that it needs highcharts as a global dependency, in which it tells you to add a script tag into your html:

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

Rather than add the above script tag into my HTML I would like to make it global via Webpack.

I have installed highcharts via npm and have tried using the ProvidePlugin and the noParse methods described here (to no avail): https://webpack.js.org/guides/shimming/#scripts-loader

For the ProvidePlugin option I used:

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

for noParse:

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

Neither worked, meaning when highcharts-ng tried to work, it gets an error because it cannot create a new Highcharts:

TypeError: Cannot read property 'Chart' of undefined

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

Here is my angular module

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

My webpack config:

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

There are 1 answers

0
dotcs On

Use expose-loader and write require('expose-loader?Highcharts!highcharts'); somewhere before the first usage of Highcharts global variable. This will require highcharts and save expose it as window.Highcharts in the browser.

Under the hood webpack makes it available for you as:

/* 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)))

/***/ }