typescript es6 import syntax output es5 commonjs m

2019-06-06 22:14发布

问题:

So the issue I have is that I am trying to use knockout-es5 and output to common js format, but I am writing everything using the es6 syntax.

Now the problem I have is that I do the following:

import ko from "knockout-es5";

with the hope that the output when ran through tsc would be:

var ko = require("knockout-es5");

However first of all it wont compile because of the knockout-es5 descriptor file doesnt have a module export, so I went in and added the following to the end of it:

declare var ko: KnockoutStatic; export module "knockout-es5" { export = ko; } Which then does seem to work, but if you look at the output where it gets used it makes it do ko.default.yourMethod rather than ko.yourMethod which then doesn't work.

So I am a bit baffled, as I love the ES6 syntax and my code is all written using ES6 imports and exports, but as I am dependent upon non ES6 exported modules I cannot seem to find a workable middle ground, I either remove the knockout default export and no require is included in the output file, or I add the default export and it adds the default property.

So is there a way to have my cake and eat it here?

回答1:

You probably want

import * as ko from "knockout-es5";

Your original import is the same as import {default as ko} from ....

Refer to http://www.2ality.com/2014/09/es6-modules-final.html for a comprehensive explanation of the syntax.