TypeScript compilation of RequireJS module generat

2020-03-18 02:49发布

问题:

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.