Skip to content

import type should not need runtime modules supportΒ #44549

Closed
@antoinep92

Description

@antoinep92

Suggestion

πŸ” Search Terms

import type
module
--outFile

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Intuitively I expect import type to be a compile-time only construct. This is currently not really the case, because using import type triggers the compiler into thinking we are using ES modules.

πŸ“ƒ Motivating Example

Consider this test.ts:

import type { mkdir as mkdir_proto } from 'fs';
const { mkdir } = require('fs') as { mkdir: typeof mkdir_proto };

This to compile to a Ε§est.js which is more or less:

"use strict";
const { mkdir } = require('fs');

Which does not use ES modules. Nevertheless, the compiler refuses to compile this if modules are disabled, e.g.
tsc test.ts --outFile test.js --target es2020 fails with:

error TS6131: Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'.

1 import type { mkdir as mkdir_proto } from 'fs';

Which makes me think the compilers treats import and import type the same way.

πŸ’» Use Cases

This is clearly not a showstopper, more of an optimization. One use-case is trying to build simple Node.JS scripts, written in typescript as a single file (with the --outFile flag), in order to deploy each script as a single javascript file, that I can run natively on a Node.JS server with no typescript support (no tsc or ts-node installed).
Since the script only has dependency to node's standard library, I was not expecting typescript to refuse to compile as a single file.

We can work arround by defining a tsconfig.json and building in a directory, then extracting the js file generated in that build/ dir. And I realize there are a lot of issues around here about packaging as a single file. But in this case, there is no concatenation required at all. This is just about import type triggering typescript into thinking we are using modules, when we really aren't.

As I said, this is clearly not critical, and I have no idea if this would be easy to implement. So it's really just a suggestion :)

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