How to make a node_module global with the power of Webpack 2

I'm currently utilizing a package in an Angular project that can be found at the following link:

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

One of the requirements for this package is that highcharts needs to be included as a global dependency by adding a script tag to your HTML like so:

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

However, instead of directly inserting the script tag into my HTML file, I prefer to make it a global dependency via Webpack.

I've installed highcharts using npm and have attempted to use both the ProvidePlugin and noParse methods as detailed here (without success): https://webpack.js.org/guides/shimming/#scripts-loader

For the ProvidePlugin method, I tried:

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

and for noParse:

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

Unfortunately, neither of these approaches worked. This resulted in an error when highcharts-ng attempted to function because it was unable to instantiate 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 the angular module being used:

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

And here is my webpack configuration:

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'] },
          },
        ],
      },
    ],
  },
}

Answer №1

To utilize the expose-loader, simply include the code

require('expose-loader?Highcharts!highcharts');
before using the Highcharts global variable for the first time. This action will import Highcharts and make it accessible as window.Highcharts in the browser.

Internally, webpack facilitates this process by:

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

/***/ }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through elements within underscore.js templates

Can someone please help me out? I'm finding this task more difficult than it should be, so I must be overlooking something simple... I am working with a variable that is acting as an underscore template. Here is an example of the code snippet: var t ...

While the data from Angular $resource can be viewed, it is not accessible in the code

As a newcomer to Angular, I'm facing a frustrating issue that I need help with. My $resource is fetching data from the server in key/value pairs like detail.name and detail.email. While I can access this data using {{detail.name}} in the view, I&apo ...

Should mutators be encapsulated within a class contained in a JS Module for better code organization and maintainability?

In order to maximize functionality of our new product using JavaScript, we have implemented an Authentication module that manages a tokenPromise which is updated upon user logins or token refreshes. It seems imperative to allow for mutation in this process ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

What is the best method for disabling autoscroll for a specific div id when the :target attribute

I created this accordion menu using only html and css, but the buttons are built with the :target id. Is there a way to prevent the automatic scrolling when any button is clicked without using javascript? It currently moves to the anchor #id. I've se ...

Having trouble with managing state changes in a React application using Multiple Checkbox components from M

Trying to update the state of multiple checkboxes and then send a POST request. Visually, the checkboxes change, but the form data remains unchanged. Here is the code snippet: export default function AccountInformations(props) { // const { enqueueSnack ...

Retrieving information from an Express.js API using React.js. Postman requests are successfully communicating with the API

Hey there, I'm facing a little issue and could use some help. I have an Express application that is working perfectly with requests from Postman (adding, deleting, etc.). Now, I want to connect my client side (React.js) with the existing API using the ...

Retrieving information from MongoDB to populate the Redux store

Currently, I have successfully set up my Node API and MongoDB. My next focus is on integrating Redux into my application. Below are some code snippets that I would like to share: The Server Order controller is functioning as expected : const getTotal = as ...

Sending the selected object from a dropdown in React back to its parent component

I have encountered a few issues with my React dropdown component. My main goal is to pass the selected object from the dropdown back to the Parent component. Currently, the dropdown list is functional and I am able to pass {this.state.selectedUser} back to ...

I encountered an error while using react-create-app: "./src/index.css (./node_modules/react-scripts/node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1"

Recently, I started a project with create-react-app and everything was smooth sailing until this morning. Even the font wasn't causing any issues. Upon running npm start, I encountered the following error message: ./src/index.css (./node_modules/react ...

Tips for refining search criteria with a combination of checkbox and range slider in Angular 2

In an attempt to refine the results for the array "db," I have implemented three filters: price, duration, and category. I have experimented with using the filter() method to apply these filters. You can find the code I have worked on here: https://stack ...

How can I retrieve a DOM object following an AJAX request?

My AJAX call fetches and appends HTML content to the current page. I hope to access this newly added HTML using standard jQuery selectors. Here's my desired approach... $.ajax({ url: url, success: function(data) { $('body').app ...

What is the best way to retain checkbox states after closing a modal?

I have a modal that includes multiple checkboxes, similar to a filter... When I check a checkbox, close the modal, and reopen it, the checkbox I clicked on should remain checked. (I am unsure how to achieve this :/) If I check a checkbox and then click t ...

Is there a way for me to manually initiate a digest cycle on the parent scope based on my instructions?

I am struggling with getting a directive to render automatically when a change is made to the underlying model programmatically. Using $scope.$apply seems like the right approach, but unfortunately it's not working as expected. The directive only rend ...

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

Manipulate the value(s) of a multi-select form field

How can you effectively manage multiple selections in a form field like the one below and manipulate the selected options? <select class="items" multiple="multiple" size="5"> <option value="apple">apple</option> <option va ...

What is the process of adding new fields to a model in TypeScript?

I have created a test.model.ts file: export interface ITransaction { description: string; transactionDate: string; isDebit: boolean; amount: number; debitAmount: string; creditAmount: string; } export class Transaction implements ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

What is the best way to include a title and a close button at the top of a menu, before the first item, when a button menu is clicked in material-ui?

One of the challenges I'm facing is adding a title to an icon button menu that contains a checkbox list of menu items. When the user clicks on the icon and opens the dropdown, I want the title to appear at the top of the dropdown along with a close bu ...

Issue with integrating Razorpay into a Node.js Express application

I am currently working on setting up a checkout page using nodejs and express with Razorpay as the payment gateway. The issue arises when trying to run the checkout() function by clicking the "Checkout" button within my shopping-cart.hbs file. Despite havi ...