Ad

Typescript Intellisense Without Emitting Require

My HTML contains this:

<script src="js/vendor/react.js"></script>
<script src="js/vendor/react-dom.js"></script>
<script type="text/javascript" src="my-react-component.js"></script>

...and I'm trying to write a simple TSX file, in Visual Studio 2015, to be transpiled into my-react-component.js:

/// <reference path="../../typings/tsd.d.ts" />

class ExampleApplication extends React.Component<any, {}> {
  render() {
      return <p>{this.props.message}</p>;
  }
};

ReactDOM.render(
    <ExampleApplication message="Hello, world" />,
    document.getElementById('container')
);

I already imported the react.d.ts and react-dom.d.ts from DefinitelyTyped and included them in my tsd.d.ts

The problem is: TypeScript will not recognize "React" and "ReactDOM" unless I explicitly import them, with:

import * as React from "react"; 
import * as ReactDOM from "react-dom";

And that works fine for editing the .tsx (in fact I get full IntelliSense for those namespaces).

But the transpiled .js - using the "React" JSX compilation option - includes the unwanted requires:

var React = require("react");
var ReactDOM = require("react-dom");

Which cause an error on the page execution, because both React, and ReactDOM are global names defined by react.js and there is no "require" function available.

Isn't there a way to declare those names to TypeScript, without emitting the actual require for each of them?

Otherwise - what is wrong in what I'm trying to do? What am I missing?

Ad

Answer

Isn't there a way to declare those names to TypeScript, without emiting the actual require for each of them?

There is. Use the global versions of the TypeScript definitions : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react/react-global.d.ts

Otherwise - what is wrong in what I'm trying to do? What am I mising?

Using global modules is a bad idea. You will run into issues as soon as you scale to about 50 files (happens very quickly) https://github.com/TypeStrong/atom-typescript/blob/master/docs/out.md

Ad
source: stackoverflow.com
Ad