TypeScript compilation of RequireJS module generates line Object.defineProperty(exports, “__esModule”, { value: true }); How to get rid of it?

坚强是说给别人听的谎言 提交于 2019-12-19 06:18:07

问题


This is how my tsconfig.json file looks:

{
    "compileOnSave": true,
    "compilerOptions": {
        "module": "amd",
        "noImplicitAny": false,
        "removeComments": false,
        "preserveConstEnums": true,
        "strictNullChecks": true,
        "sourceMap": false
    }
}

I have a typescript file named a.ts which is an AMD module (I'm using requirejs), which looks like:

export function a() {
    var a = {
        b: 5
    };
    return a;
}

The compiled Javascript files looks like:

 define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function a() {
        var a = {
            b: 5
        };
        return a;
    }
    exports.a = a;
 });

I need my generated JavaScript file to be:

define(function () {
    "use strict";
    var a = {
        b: 5
    };
    return a;
});

So I need to
a) Remove the Object.defineProperty(exports, "__esModule", { value: true }); line
b) Remove the require and exports dependencies from define
c) Not having an internal function "a" and then expose "a" on exports, but rather simply return "a" object in the a.js file

What changes do I need to make to tsconfig.json and a.ts files to get the desired Javascript file or something closer to it, any improvements from current a.js towards what I need would be great, even 1 or 2 out of 3 requirements.

One way is to make a.ts exactly like my desired a.js file and then compile, but I must use export statement way of making amd module due to another unrelated requirement. Thanks for reading till here. Please help.


回答1:


Your export issue can easily be fixed by using the export = syntax. If you code your module with this:

var a = {
  b: 5
};

export = a;

It is transpiled to this:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var a = {
        b: 5
    };
    return a;
});

Note that you also lose the creation of the __esModule property.

The rest of your question duplicates another question. In brief, the TypeScript compiler provides no option to avoid emitting the require and exports dependencies. You have to process the emitted code on your own if you want to remove them.



来源:https://stackoverflow.com/questions/47297768/typescript-compilation-of-requirejs-module-generates-line-object-defineproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!