'What's the purpose of `Object.defineProperty(exports, "__esModule", { value: !0 })`?
I read minimized tensorflow.js file for understanding module structure. Tensorflow.js is written in typescript and the above file(link) may be result of transpiling.
Anyway, I understood this module written with IIEF pattern for UMD module format. But, at end of factory function, Object.defineProperty(exports, "__esModule", { value: !0 }) exists. I know its grammatical meaning. But I do not know the purpose of this code. As far as I googled, this code seems to mark the module as ES Module. But it is not clear enough to me. So, some questions follow.
- This code seems to be removable. Does it really?
- Are there any cases for using this property?
Solution 1:[1]
It helps to correctly import a default export in CommonJS/AMD/UMD module format.
A default import (i.e. import d from "foo") for a CommonJS/AMD/UMD module is equivalent to
const d = require("foo").default
But most of the CommonJS/AMD/UMD modules available today do not have a default export, making this import pattern practically unusable to import non-ES modules (i.e. CommonJS/AMD/UMD). For instance
import fs from "fs"
or
import express from "express"
are not allowed.
To allow default imports in CommonJS/AMD/UMD (e.g. import fs from "fs"), the typescript compiler adds __esModule flag and checks it in a transpiled code (from ES6 to CommonJS). It imports default exports by using an __importDefault helper function (which checks the __esModule flag).
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
}
exports.__esModule = true;
var bar_1 = __importDefault(require("bar"));
Solution 2:[2]
Maxim had a great answer.
It could be also helpful to poke around with typescript playground with https://www.typescriptlang.org/tsconfig#esModuleInterop flag on/off.
off
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const foo_1 = require("foo");
console.log(foo_1.default);
on
"use strict";
+ var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
Object.defineProperty(exports, "__esModule", { value: true });
- const foo_1 = require("foo");
+ const foo_1 = __importDefault(require("foo"));
console.log(foo_1.default);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maxim T |
| Solution 2 | lxyyz |
