Using the name generated by the compiler can be risky as it may change unexpectedly.
A Solution
One workaround is to do the following:
import myModule from 'module'
const module = myModule
The above code will compile to:
var module = module_1.default;
This way, you can safely use the variable module
.
Benefits of using export default
over export =
In the future, using export default
will likely become the standard practice. This feature has been designed by ECMAScript to replace the current CommonJS usage. The default
member is more versatile and efficient.
For example, if you need to export an object like this:
const myConfigObject = Object.freeze({
dbHost: "",
dbUser: "",
// ...
})
export = myConfigObject
You can then import it using:
import * as myConfigObject from "./myConfigObject"
If you want to also export a helper function like toDSN
, doing so within the configuration object may not be the most elegant solution. Instead, in ES6 you can do the following:
export default Object.freeze({
dbHost: "",
dbUser: "",
// ...
})
export function toDSN(configObj) {
return // ...
}
You can then import the default object:
import myConfigObject from "./myConfigObject"
... or import just toDSN
:
import { toDSN } from "./myConfigObject"
... or import both:
import myConfigObject, { toDSN } from "./myConfigObject"
One limitation for Node.js users with the current setup is that they must specifically reference the default
member. However, once Node.js supports ES6 modules, this won't be necessary anymore.
Reasons behind TS Compiler's Intermediate Variable Generation for Imports
The TS compiler generates intermediate variables for imports because this method is needed for the general case of ES6 modules. For instance, when importing multiple variables in ES6:
import myConfigObject, { toDSN } from "./myConfigObject"
In CommonJS or AMD, only single variable imports are allowed. So, the compiler creates an intermediate variable like myConfigObject_1
. This allows access to myConfigObject
through myConfigObject_1.default
and toDSN
through myConfigObject_1.toDSN
.
I recommend reading this article on ES6 modules for further information.