Reputation: 148514
I have a simple file which is using es6 module loader :
1.ts
import {foo} from "./2"
foo('hello');
2.ts
function foo (a){console.log(a);};
export {foo}
When tsconfig is set to :
"module": "commonjs",
We can see that it converts import
to require
:
(output)1.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var _2_1 = require("./2");
_2_1.foo('hello');
That's fine. But if I now use module loading via require
:
1.ts
var a = require("./2")
a('hello');
2.ts
function foo (a){console.log(a);};
module.exports.foo= foo
And set "module": "es6",
: then the output is :
(output)1.js
var a = require("./2"); // why it didnt compile it to `import` ??
a('hello');
Question:
What is the reason that TS can't compile require
to import
?
Upvotes: 0
Views: 1467
Reputation: 250812
TypeScript normalised their syntax on the ECMAScript version of the import syntax. All of your TypeScript code should use this style:
import { ZipCodeValidator } from "./ZipCodeValidator";
The compiler will happily convert this into the AMD, CommonJS, or System style of imports - but it doesn't unidirectionally map from each of these to each other one of these.
So the short version is, write ECMAScript imports and use the compiler flag to have them converted into whatever you like.
As an aside, when actually intending to use the ECMAScript module loader, adding .js
works within the import statement - i.e. TypeScript understands what you mean.
Upvotes: 2