Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  1. This code seems to be removable. Does it really?
  2. Are there any cases for using this property?
like image 852
Hyuck Kang Avatar asked Jun 20 '18 08:06

Hyuck Kang


People also ask

What is Esmodule?

ES Modules is the ECMAScript standard for working with modules. While Node. js has been using the CommonJS standard for years, the browser never had a module system, as every major decision such as a module system must be first standardized by ECMAScript and then implemented by the browser.

What does exports do in Javascript?

The export statement is used in Javascript modules to export functions, objects, or primitive values from one module so that they can be used in other programs (using the 'import' statement). A module encapsulates related code into a single unit of code. All functions related to a single module are contained in a file.

What keyword is used to bring module exports into scope?

require keyword refers to a function which is used to import all the constructs exported using the module. exports object from another module.


1 Answers

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"));
like image 84
Maxim T Avatar answered Oct 17 '22 20:10

Maxim T