phantom phantom - 5 months ago 35
Javascript Question

using library without 'require' when using CDN

I want to use this Chart JS reactJs wrapper library.

I am consuming the library from a CDN as I have not set up any module bundling process for this project. I know I could, but was wondering how to use this library without using

. I think it would be useful for an answer to explain how to do this for people who are still a bit uncomfortable with some of the newer js practices.

In the react wrapper Chart JS example you will see that it shows:

var LineChart = require("react-chartjs").Line;

var MyComponent = React.createClass({
render: function() {
return <LineChart data={chartData} options={chartOptions} width="600" height="250"/>

is there anyway to assign the same value to
when using a CDN?


Just look at the file the CDN provides and find out for yourself.

It has this form:

(function (root, factory) {
    // Do some stuff to detect the environment
    // When everything fails, just assign a global variable:

    root["react-chartjs"] = factory(root["React"], root["ReactDOM"], root["Chart"]);

})(this, function ( ... ) {

Where root is the global object (window in the browser) and factory is just a function that takes the dependencies and returns the library.

To get LineChart:


Keep in mind factory needs React, ReactDOM and Chart. And assumes all these will be in a global variable named the same way.