1

Is it possible to import a module defined without a default export via: import module from 'module'; and compile it to commonjs?

This Stack Overflow Answer suggests that it is possible with the --allowSyntheticDefaultImports option passed (albeit only for systemjs modules?). The Compiler Options Documentation states that allowSyntheticDefaultImports only affects typechecking.

Are there any work arounds besides the import * from module as 'module'; syntax?

3
  • Just curiously, why does the syntax you have to use to import the module matter to you? Why don't you want to use import * from module as 'module' if it works? Commented May 1, 2017 at 16:57
  • A couple reasons: 1) It's ugly 2) It creates a difference between importing a module that intentionally does not have a default export, and a module that does have a default export, albeit in a different syntax. In theory the syntax workaround will need to be altered once (/if) the jquery.d.ts file is updated to properly (imo) export the JQuery function as a default function. Commented May 1, 2017 at 17:03
  • 1
    So ignoring #1 haha, your point #2 isn't really up to you, or up to the .d.ts file. If the actual .js file defines a default export, then the .d.ts file should contain that information and you'll likely import it using import module from 'module'; If the actual .js file only defines named exports, then the .d.ts file will reflect that and you import things using named imports or a wildcard import as mentioned in your post. TLDR: import syntax you use is determined by the shape of the actual JS module Commented May 1, 2017 at 17:09

1 Answer 1

1

What you are describing is not CommonJS...

CommonJS is the module API implemented by Node, where you use module.exports, exports and require to manage your modules.

TypeScript is a superset of JavaScript and relies on ES6 native modules. So if you do not want default exports, you should be able to do something like this:

Your module

export function foo() {
  console.log('Foo');
};

export function bar() {
  console.log('Bar');
};

Your entry point

import {foo, bar} from './module';

foo();
bar();
Sign up to request clarification or add additional context in comments.

2 Comments

I want to import JQuery (a non typescript module) into a typescript file without using the import * as $ from 'jquery'; and compile that file to commonjs.
Why didn't you put this information in your question? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.