Skip to content

Proposal: add --hoistImports to compiler options #22178

@ericanderson

Description

@ericanderson

In ES6, imports are hoisted and evaluated before code within the same file. Webpack definitely already does this and I think rollup might too (or certainly it would be legal for them to do so).

Example:

import installPolyfills from "ie-polyfills";
installPolyfills();
import Foo from "other-code";

In ES6, your code will be evaluated as

import installPolyfills from "ie-polyfills";
import Foo from "other-code";
installPolyfills();

and cause an unexpected error (polyfills aren't available for Foo) since in an ES5 engine it still behaves as the example.

Unfortunately, this allows us to write code that doesn't behave the same depending on the output module type (if TS hoisted imports when module: "es6") nor when running ES6 style code through other tools (like webpack or rollup).

This flag would instruct TS to hoist imports in generated code, regardless of the output module format. Thus one can write code that can be sure to behave the same in node 6, webpack, and engines that natively support es6 modules.

Thus, with hostImports: true and module: "cjs", your output code would be:

var installPolyfills = require("ie-polyfills");
var Foo = require("other-code");
installPolyfills();

I think that ideally this flag would default to true when module: "es6" however that would likely be considered a breaking change. So perhaps that change (or always defaulting it to true, since TS looks like ES6) could happen in TS3.

Thanks
CC @mhegazy

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions