Search code examples
javascripttypescriptmoduleecmascript-next

Typescript won't emit import statements as-is


My index.html imports only one script with <script type="module" src="./index.js"></script>

And at the top of index.ts are the now-standard import statements

import { PieChart } from "./pie-chart.js";
import { ChartLegend } from "./chart-legend.js";

But index.ts, when compiled to index.js, the import statements are completely removed, replaced with nothing else. My tsconfig.json is set to

        "target": "ES2020",
        "module": "ESNext",

But regardless if "module" is set to ES6, ES2015, ES2020, or ESNext, they all work the same.

Browsers now understand the import statement natively, and will import the files correctly (assuming .js extension is there and the path is correct). I tried this by copy-pasting those import statements into the resulting .js file and everything lights up.

How could / why can't Typescript (Version 4.0.2) emit the imports??


Solution

  • Typescript drops imports from the file if the imported items are only used as types.

    import { PieChart } from "./pie-chart.js";
    
    const pie = document.querySelector("pie-chart") as PieChart;
    

    Will not cause the import to be emitted. However, you can import a module "for its side effects" with

    import "./pie-chart.js";
    

    and the import will be emitted. You can also do both.

    import { PieChart } from "./pie-chart.js";
    import "./pie-chart.js";
    
    const pie = document.querySelector("pie-chart") as PieChart;
    

    But this may not scale well for an app of any significant size.