Search code examples
reactjstypescriptimportwebpacksource-maps

Cannot import react-addons-shallow-compare, Typescript


I need to use the shallowCompare function within the shouldComponentUpdate function of a custom react component. I get the following error:

app.js:95084 Uncaught TypeError: Cannot read property 'shallowCompare' of undefined

I have installed react-addons-shallow-compare version 15.3.0 and I found it in the node_modules. It looks like this:

module.exports = require('react/lib/shallowCompare');

And this is the shallowCompare.js referenced.

/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
* @providesModule shallowCompare
*/

'use strict';

var shallowEqual = require('fbjs/lib/shallowEqual');

/**
 * Does a shallow comparison for props and state.
 * See ReactComponentWithPureRenderMixin
 * See also https://facebook.github.io/react/docs/shallow-compare.html
 */
function shallowCompare(instance, nextProps, nextState) {
  return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState);
}

module.exports = shallowCompare;

I have also installed the typings. I have this version:

// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6a36f6d5b61602b6c4ad932599097135e80abaf4/react/react-addons-shallow-compare.d.ts
declare namespace __React {
    namespace __Addons {
        export function shallowCompare<P, S>(
            component: __React.Component<P, S>,
            nextProps: P,
            nextState: S): boolean;
    }
}

declare module "react-addons-shallow-compare" {
    var shallowCompare: typeof __React.__Addons.shallowCompare;
    export = shallowCompare;
}

And now I am trying to import it and use it in one of my files. I have tried every strategy for importing it.

import { __Addons as ReactAddons } from "react";

/* ... other stuff ... */

ReactAddons.shallowCompare(this, nextProps, nextState);

Or

import shallowCompare = require("react-addons-shallow-compare");

/* ... other stuff ... */

shallowCompare(this, nextProps, nextState);

Or

import shallowCompare = __React.__Addons.shallowCompare;

/* ... other stuff ... */

shallowCompare(this, nextProps, nextState);

In the last case, the error I get is not the one mentioned above, but

Uncaught ReferenceError: __React is not defined

As a mention, I am using Typescript 1.8.10.

For what it's worth, I am also getting the following error:

Failed to parse SourceMap

I am quite stuck on this for a while now. Some help would be greatly appreciated.

Thanks!


Solution

  • import * as shallowCompare from "react-addons-shallow-compare"; works!

    If someone wants to explain why and would like to edit this answer, I would be really grateful.