Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fails to import commonjs module without default export when transpiling typescript #238

Closed
iki opened this issue Jun 8, 2018 · 4 comments

Comments

@iki
Copy link

iki commented Jun 8, 2018

Example module classnames@2.2.5, see JedWatson/classnames#105.

In typescript, we use import * as cn from 'classnames' to import from module without default export.

This gets transpiled using babel's _interopRequireDefault to

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _classnames = __webpack_require__(/*! classnames */ "../node_modules/classnames/index.js");
var _classnames2 = _interopRequireDefault(_classnames);

resulting in cn equal to { default: classNames() } instead of classNames() function, and throwing Uncaught TypeError: cn is not a function.

Is there any way to fix it and handle such exports correctly?

@alangpierce
Copy link
Owner

Hi @iki, take a look at the enableLegacyTypeScriptModuleInterop option described here: https://github.com/alangpierce/sucrase#legacy-commonjs-interop . I think that should fix it for you.

The import * approach works with the default TypeScript settings, but it's probably a good idea to enable TypeScript's --esModuleInterop setting, which changes the import behavior to be the same as various other tools. In that case, you'd write it as import cn from 'classnames';.

@alangpierce
Copy link
Owner

I think enableLegacyTypeScriptModuleInterop should solve this problem, so I'll close this, but let me know if you run into any trouble!

@iki
Copy link
Author

iki commented Jun 11, 2018

@alangpierce thanks, works perfectly! and sorry for overlooking it in docs :)

will definitely switch to esModuleInterop when we upgrade from typescript@2.6

@alangpierce
Copy link
Owner

Cool, glad to hear!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants