Highcharts: "Highcharts not defined" as ES6 imports (browserify, babel)

Created on 3 Feb 2016  ·  36Comments  ·  Source: highcharts/highcharts

I've tried everything possible to get Highcharts to work with Babel / Browserify / ES6 imports. I'm getting a ReferenceError: Highcharts is not defined error. I was previously using highstock-browserify but it broke after the adaptor was removed.

I did a

npm install highcharts --save-dev

I've done a

//highcharts libraries
import Highcharts from 'highcharts/highstock';
import 'highcharts-ng'; //angular highcharts bindings

If I look in dev tools the file is being imported fine:

image

Any help appreciated. Possibly related issue on stackoverflow.

EDIT:

Also tried, in desperation ( :P ) with highcharts-release package.

And more. I've also tried the recommended method. File appears to be included in the source, but Highcharts is still undefined.

//highcharts libraries
let Highcharts = require('highcharts/highstock');
import 'highcharts-ng';

CC- @laytzehwu

Docs Enhancement

Most helpful comment

I'm using webpack ng es6, and the only way I've gotten it to work is with

var Highcharts = require('highcharts/highstock');
window.Highcharts = Highcharts;
require('highcharts/modules/exporting')(Highcharts);

If someone knows how to get this to work with using import syntax, please reply

All 36 comments

I'm using webpack ng es6, and the only way I've gotten it to work is with

var Highcharts = require('highcharts/highstock');
window.Highcharts = Highcharts;
require('highcharts/modules/exporting')(Highcharts);

If someone knows how to get this to work with using import syntax, please reply

@jon-a-nygaard

Thanks for reporting! We will look into this as soon as possible. In the meantime, you could have a look at webpack with a babel-loader as an alternative.

Hi, @jon-a-nygaard. Webpack is definately the way forward. We're going to use that in the next project. This project however is a bit too mature with quite a number of browserify custom bundles. Do let me know if you figure this out.

Okay. @ragefuljoe - the window.Highcharts = Highcharts was what was needed. It works with this import syntax!

import Highcharts from 'highcharts/highstock';
window.Highcharts = Highcharts; //this line did the magic
import 'highcharts-ng';

Should we close this or do you guys want to bind window.Highcharts inside your code? I think this should be added to the main docs or somewhere.

@piggyslasher Glad the workaround from @ragefuljoe helped you. I will leave this issue open, so we can work on improving loading Highcharts with ES6 imports.

I think this should be added to the main docs or somewhere.

Indeed, I will add the workaround as a note to the Install from npm article.

that's cool @piggyslasher. any luck importing exporting.js with import syntax?

_update_
here're all my highcharts related lines, with maps needed as well:

import Highcharts from 'highcharts/highstock';
window.Highcharts = Highcharts;
require('highcharts/modules/map')(Highcharts);
require('highcharts/modules/exporting')(Highcharts);
require('./pages/home-page/world'); //I'm downloading this from example links. any better way?
import 'highcharts-ng';

Is there better way to handle the specific map data? E.g., I'm downloading and explicitly including world.js here (other option is to get the json from the backend, which I might do)

I'm having exactly the same issue. All I want to do in my project is import 'Highcharts' and be done with it. All the other major JS libraries "just work" out of the box and I can't understand why Highcharts does not.

@jon-a-nygaard @TorsteinHonsi - it might be worth looking at how Angular, lodash, underscore, ui-router and the myriad of other JS libraries expose their functionality for browserify/webpack etc and duplicate it in highcharts.

@romiem Thanks for the tip. I am currently working on a fix for this, planning to get it into our next maintenance release.

Hi,
I'm having a similar issue with highcharts 4.2.5. I'm following the article Use Highcharts to create charts in React .
If I use the import syntax, that is import Highcharts from 'highcharts', I get the error Uncaught TypeError: _highcharts2.default[(this.props.type || "Chart")] is not a constructor.

When I use the syntax suggested by @ragefuljoe, it works! however, that makes me think, how about using 'highcharts/highstock instead of 'highcharts'? well, it works with the import syntax. What's the difference, or is it thought to work that way and I was using the import wrongly?

Here is the complete (working) code:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Highcharts from 'highcharts/highstock';
class Chart extends Component {
    constructor(props) {
        super(props);
    }
    // When the DOM is ready, create the chart.
    componentDidMount() {
        // Extend Highcharts with modules
        if (this.props.modules) {
            this.props.modules.forEach(function (module) {
                module(Highcharts);
            });
        }
        this.chart = new Highcharts[this.props.type || "Chart"](
            this.props.container, 
            this.props.options
        );
    }
    //Destroy chart before unmount.
    componentWillUnmount() {
        this.chart.destroy();
    }
    //Create the div which the chart will be rendered to.
    render() {
        return React.createElement('div', { id: this.props.container });
    }
}
export default Chart;

Thanks @jon-a-nygaard for letting me know about this thread.

👍 to enhanced Webpack support. I've been doing all my React/Highsoft experiments in CodePen, but will be moving to a proper node env soon. Webpack/Import/ES6 is good stuff.

React w/MDL & Highstock (test)

Are there any news about "simple" import { Highcharts} from "highcharts" module in typescript/angular 2 applications with highcharts 5? Only found the docs about "require Highcharts" which is always a little bit hacky...

@jon-a-nygaard

@Skuriles What type of bundler (e.g. Webpack, Browserify) are you using? Here's an example of how you can use Highcharts with ES6 and Babelify

@jon-a-nygaard I'm using SystemJs

@Skuriles Here's an example of how I used Highcharts with SystemJS. Hope it helps, if not please let me know.

Will try it as soon as possible and post solution here!
Thank you very much for your example!!

I changed my code due to your proposal, but I still get typescript errors from intellisens and also the gulp-typescript compiler throws errors. It works in the compiled app but this is not satisfying.

import Highcharts from 'highcharts/highstock.js" is still an unknown module.

I also tried with typescript-babel plugin but this throws compiler for other things.

So finally I went to back to load the highstock.js file directly without systemjs and just declare Highcharts in the TS file to prevent compile errors.

I wait for a real ES6 module but for now we can live as it as we will probably switch to precompiled, bundled versions without systemjs for release!

@jon-a-nygaard I am not able to render my highchart in my recat app. All I am getting is a blank screen. This is what I am doing for my highchart:

import React, {Component, PropTypes} from 'react';
import Highcharts from 'highcharts/highcharts';
import styles from './styles/linechart.css';
import cssModules from 'react-css-modules';
import request from 'axios';
import moment from 'moment';

@cssModules(styles)
class LineChart extends Component {
    constructor(props) {
        super(props);
    }

    static propTypes = {
        modules: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.object,
            PropTypes.array
        ]),
        container: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.object,
            PropTypes.array,
        ]),
        options: PropTypes.oneOfType([
            PropTypes.object,
            PropTypes.array
        ]),
    };

    highchartsModules() {
        if (this.props.modules) {
            this.props.modules.forEach(function(module) {
                module(Highcharts);
            });
        }
    }

    componentDidMount() {

        const inComing = [];
        const outGoing = [];
        const xAxisData = [];

        request.get('/dashboard/hourly', {
            params: {
                timezone: moment().utcOffset(),
                date:     '2016-07-06'
                // date:     moment(new Date()).format('YYYY-DD-MM')
            }
        }).then(response => {
                response.data.forEach(item => {
                    const flattened = {};
                    const out = {};
                    flattened.name = item.date;
                    flattened.y = item.inCount;
                    out.name = item.date;
                    out.y = item.outCount;
                    xAxisData.push(item.hour);
                    inComing.push(flattened);
                    outGoing.push(flattened);
                });
            });

            console.log('InComing data: ', inComing);
            console.log('OutGoing data: ', outGoing);
            console.log('X Axis data: ', xAxisData);

            const chartOptions = {
                tooltip: {
                    borderRadius:    20,
                    backgroundColor: 'rgba(18, 21, 23, 0.9)',
                    style:           {
                        color: 'white',
                    },
                    shadow: false,
                },
                title: {
                    text: ''
                },
                subTitle: {
                    text: ''
                },
                xAxis: {
                    categories: xAxisData,
                    labels:     {
                        enabled: false
                    },
                    crosshair: {
                        width:     1,
                        dashStyle: 'Dash',
                        color:     'black',
                        snap:      false,
                    },
                    tickInterval: 2
                },
                legend: {
                    enabled: false,
                },
                series: [{
                    name: 'Incoming Calls',
                    data: inComing
                }, {
                    name: 'Outgoing Calls',
                    data: outGoing
                }
            ]
        };

        this.highchartsModules();
        console.log('CHART OPTIONS: ', chartOptions);
        if (typeof window !== 'undefined') {
            this.chart = new Highcharts['Chart'](
                this.props.container,
                chartOptions
            );
        }
    }

    render() {
        const { container } = this.props;
        return (
            // <div styleName="chart">
                <div class="chart" id={container} />
            // </div>
        );
    }
}

export default LineChart;

and I am using this highchart in the following way in my app:

<LineChart container="chart" type="chart" />

Any help appreciated. Thanks in advance.

So far I got it to work.

import Highcharts from "highcharts";

systemjs
map:
'highcharts': "npm:highcharts"
package:
'highcharts': { main: "highstock", defaultExtension: "js"}

only problem:
compiler throws errors because @types/highharts has the following problem:
Property 'StockChart' does not exist on type 'Static'.

but the app works at least

In case someone might need it with Rollup

I have the following setup which is working.

In a vendor.ts file I have

import * as _highcharts from 'highcharts/highcharts';
...
export default {
   ...
   _highcharts
};

Which creates a vendor bundle.
Then in my app.rollup.js (config file to create my app bundle).

export default {
    entry: 'src/main.ts',
    dest: 'bundles/app.js',
    format: 'iife',
    sourceMap: true,
    moduleName: 'app',
    plugins: [
        ...
    ],
    external: [
        'highcharts/highcharts'
    ],
    globals: {
        ...
        'highcharts/highcharts': 'vendor._highcharts'
    }
};

And finally in my application I can use

import Highcharts from 'highcharts/highcharts';

@jon-a-nygaard Unfortunately your example does not work with typescript compiler. I get 'highchart' has no default export error.

@Skuriles thanks your approach works but I did a plain and simple ..

import 'highcharts';

(in addition to your other suggestions)

Thanks

None of the solutions above worked for me in the latest typescript version for me the below one did work:

import Highcharts from 'highcharts/highcharts.src.js';
import {default as HighchartsMore} from 'highcharts/highcharts-more.src.js';
HighchartsMore(Highcharts);

For those of you working with Highcharts in TypeScript, I have created a simple example of a working setup. What to take note of from this example is that loading Highcharts should be done as following:

import * as Highcharts from 'highcharts'
import * as HighchartsMore from 'highcharts/highcharts-more.src.js'
HighchartsMore(Highcharts)

The reason why import Highcharts from 'highcharts' does not work, is that such a syntax requires our modules to export a default, which they do not. For those interested, Typescript has a good documentation on various forms of importing.

Hi Jon, in my case it is working fine in google chrome and also showing the charts. But these charts are not coming in case of mozilla and also not giving any error in console. Give me some solution how to solve.

Any one who solve this please help

Hi @Sandipj38,

It doesn't sound like issue with ES6 imports. Could you create a topic on our forum or send us an email (details)? Thanks!

Hello,
I am using webpack, with react and highcharts. I am getting an error with

Uncaught TypeError: _highcharts2.default[(this.props.type || "Chart")] is not a constructor

I've gone though this issue and I've not been able to find a solution. I've tried every possible permutation and combination of import/require 'highcharts', 'highcharts/highstock,'highcharts.js' and now I am completely out of options.

var Chart = React.createClass({ componentDidMount: function () { // Extend Highcharts with modules if (this.props.modules) { this.props.modules.forEach(function (module) { module(Highcharts); }); } // Set container which the chart should render to. this.chart = new Highcharts[this.props.type || "Chart"]( this.props.container, this.props.options ); }, //Destroy chart before unmount. componentWillUnmount: function () { this.chart.destroy(); }, //Create the div which the chart will be rendered to. render: function () { return React.createElement('div', { id: this.props.container }); } }), element2;

Could you please help me out here?

@satishrao84 it might be worth looking at https://github.com/kirjs/react-highcharts , it's worked well for me

I was able to get Highcharts and Highstock working with ES6 imports using webpack successfully with a theme as well all contained in the bundle,js file.

I wrote about the problem on the highcharts-ng repo here https://github.com/pablojim/highcharts-ng/issues/624

The solution was to import highcharts/highstock, then theme, then highcharts-ng in my main app and then add Highcharts in a bundle global in my webpack config and it worked.

*Note: I had to downgrade to highcharts-ng v1.0.1 because 1.1.0 includes Highcharts 5 and forces the Highcharts product to be used. I needed Highstock and reverting back to v1.0.1 doesn't include Highcharts dependency so I could use Highstock v6 and my theme in my bundle without double or triple loading Highcharts on the client side.

EDIT: i was able to get exporting working as well with import ES6 syntax

import Highcharts from "highcharts/highstock";
import "../../js/highcharts.theme";
import "highcharts-ng";
import Exporter from "highcharts/modules/exporting";

// connect exporter to Highcharts bundle global
Exporter(Highcharts);

And in webpack.config setup the Highcharts global for the theme.

  plugins: [
    new webpack.ProvidePlugin({
      jQuery: "jquery",
      $: "jquery",
      "window.jQuery": "jquery",
      Highcharts: "highcharts/highstock"
    })
  ]

@satishrao84 i was getting the same error when i tried to use a highstock chart but was only loading highcharts. check in your webpack bundle.js for Highstock JS and see if it is being packed into it or if Highcharts is instead. see my comment above on loading highstock with import. i have highstock and a theme working with highcharts-ng but cannot get the exporter to work yet even though it is in the bundle.js and is getting Highcharts injected the menu icon doesn't showup yet on my chart.

This issue is now considered closed, due to updates done in commit 7da7361. This commit improves our documentation on how to load Highcharts in ES6, which I have considered to be the reccuring problem here. I will also apply these updates to www.highcharts.com/docs as well.

Over time this issue has developed into a mix of many different, but similar issues which has become a little difficult to track. If anyone is experiencing a similar problem to this topic, please create a new issue, as it will be easier to then give you appropriate help.

For those who are awaiting our ES6 modules, please follow issue #7186.

Should there be any questions regarding this topic, please give us a comment.

Best regards

it took me a while to find it but i end up using expose

simple install highcharts
and then
import 'expose?highcharts!highcharts/highcharts';

The problem with @omer123456 's solution is that you'd get error

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.
                 You need to specify 'expose-loader' instead of 'expose',
                 see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

One way that works is
in your main js

import Highcharts from 'highcharts';
import 'highcharts-ng'

And then add a new rule in the webpack.config.js

{
   test: require.resolve('highcharts'),
   use:[{
            loader: 'expose-loader',
            options: 'Highcharts'
   }]
}

This also resolves the issue of Cannot read property 'Chart' of null

It's mentioned on this thread, but easy to miss; the latest version of highcharts has real es6 modules that work as expected :

https://github.com/highcharts/highcharts/issues/7186

Although it appears the mention of them is still missing from the online docs-

Was this page helpful?
0 / 5 - 0 ratings