Typescript: Translate wrongly for JQuery TypeScript

Created on 26 Oct 2016  ·  5Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 2.0.3 / nightly (2.1.0-dev.201xxxxx)

Code

// A *self-contained* demonstration of the problem follows...
import jq from "jquery";
jq('#pnlTest').text(apple.eat());

Expected behavior:
const jquery_1 = require("jquery");
jquery_1('#pnlTest').text(apple.eat());
Actual behavior:
const jquery_1 = require("jquery");
jquery_1.default('#pnlTest').text(apple.eat());

Working as Intended

All 5 comments

These issues should be raised at DefinitelyTyped/DefinitelyTyped as they are third party typings not directly managed by this repository.

@kitsonk That doesn't effect the TypeScript emit, the behavior here has to do with allowSyntheticDefaultImports and misunderstandings related ES6 code consuming commonjs when an interop aware environment does a mapping like exports.default = module.exports.

At any rate the emitted code is correct, and if it TypeChecks, then allowSyntheticDefaultImports is true because jquery.d.ts uses

declare var $: JQueryStatic; 
export = $;

@avatar21 the translation is correct. Because the syntax

import $ from 'jquery';

is sugar for the precisely equivalent

import { $ as default } from 'jquery';

which is precisely and correctly transpiled to

const $_1 = require("jquery");
$_1.default('#pnlTest').text(apple.eat());

when the module setting is commonjs, which it is by default.

Edit
Just to clarify, some module loaders (such as SystemJS), and transpilers (notably _not_ TypeScript) use a runtime check and an auto-mapping to allow modules in commonjs format to be imported with the ES6 import sugar.

It is still confusing for new comers to TypeScript, especially they have experience with Babel.
I also encounter these problems when using new library of which the document is written in ES6 (because they also support commonjs).

If you are using commonjs, I still think import $ = require('jquery') is the least confusing one, for now. Though it has been deprecated. In future nodejs will have official module specs.

Default imports import the default. That's what it means.

Was this page helpful?
0 / 5 - 0 ratings