Skip to content

Missing async keyword when using import() while outputting CommonJS modules #49652

@kaylendog

Description

@kaylendog

Bug Report

🔎 Search Terms

missing, await, async, commonjs, import, dynamic import, syntax error

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about the dynamic import function
  • TypeScript versions: next, 4.7.4, 4.6.4, 3.9.19

⏯ Playground Link

Playground link with relevant code

💻 Code

const getPath = async () => {
	/* in reality this would do some async FS operation, or a web request */
	return "/root/my/cool/path";
};

const someFunction = async () => {
	const result = await import(await getPath());
	console.log(result);
};

someFunction();

Generated JavaScript:

const getPath = async () => {
    /* in reality this would do some async FS operation, or a web request */
    return "/root/my/cool/path";
};
const someFunction = async () => {
    const result = await Promise.resolve().then(() => require(await getPath()));
    console.log(result);
};
someFunction();

The issue also occurs when both functions are exported:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.someFunction = exports.getPath = void 0;
const getPath = async () => {
    /* in reality this would do some async FS operation, or a web request */
    return "/root/my/cool/path";
};
exports.getPath = getPath;
const someFunction = async () => {
    const result = await Promise.resolve().then(() => require(await (0, exports.getPath)()));
    console.log(result);
};
exports.someFunction = someFunction;
(0, exports.someFunction)();

🙁 Actual behavior

tsc emits code without the await keyword, causing a SyntaxError at runtime:

const result = await Promise.resolve().then(() => require(await getPath()));
/Users/xxx/Projects/testing/test-ts/src/index.js:6
    const result = await Promise.resolve().then(() => require(await getPath()));
                                                              ^^^^^
SyntaxError: missing ) after argument list

🙂 Expected behavior

tsc emits code with an await included before the promise callback definition:

const result = await Promise.resolve().then(async () => require(await getPath()));

Or an equivalent promise chain:

const result = getPath().then((path) => require(path));

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions