krishnab
krishnab

Reputation: 10060

Writing Common.js modules in Typescript 2.7.2 - compilation questions

I am totally new to Typescript and Javascript as well, so this is undoubtedly a noobie question. I was looking at some Typescript 2.0 tutorials on writing modules. In the typescript documentation, the authors describe both the ES6 module import/export methods, and the CommonJS, AMD, and other import/export methods.

However, it seems that in my tsconfig.json I can specify which module handler I want to use when compiling: AMD, CommonJS, etc.

So my confusion is, can I write the import/exports using the standard ES6 statements with import {}..., and then those get converted to the appropriate CommonJS or RequireJS syntax on compilation? Or do I need to write the appropriate CommonJS/RequireJS, etc. syntax in typescript and then the compilation step will just use whatever I produce?

Upvotes: 0

Views: 281

Answers (2)

Stanislas
Stanislas

Reputation: 2020

Yes, it affects the generated code, not how you should write your code.

As a learning exercise, I'd recommend looking at the output with each of the values: None, CommonJS, AMD, System, UMD, ES6, ES2015 and ESNext.

Note that some compiler options aren't available in some configurations:

  • outFile can only be used with AMD or System
  • However ES6 / ES2015 may be used when targeting ES5 or lower

Upvotes: 2

artem
artem

Reputation: 51609

can I write the import/exports using the standard ES6 statements with import {}..., and then those get converted to the appropriate CommonJS or RequireJS syntax on compilation?

Yes exactly, import and export are part of TypeScript language, and they are virtually identical to import and export in ES6.

TypeScript will compile them according to the combination of module and target settings in tsconfig.json - if target is es6 or above (or if module itself is es6), import and export will remain in generated javascript, otherwise they will get converted to AMD or commonJS syntax.

Upvotes: 1

Related Questions