Skip to content

dynamic import closes over the module specifier argument #48285

@PsixokoT

Description

@PsixokoT

Bug Report

Dynamic import JSON compiled into js code with closures. What does not look like what was expected.

🔎 Search Terms

Dynamic import JSON

🕗 Version & Regression Information

TypeScript Version 4.6.2

  • I was unable to test this on prior versions because I think there is the same

tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "strict": true,
    "newLine": "LF",
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "esModuleInterop": true
  }
}

💻 Code

1.json

[1]

2.json

[2]

import_test.ts

function load() {
  let fileName = '1';
  const promises = [import(`./${fileName}.json`)];
  fileName = '2';
  promises.push(import(`./${fileName}.json`));
  
  Promise.all(promises).then(results => console.log(results));
}

load();

Compiled js

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
function load() {
    let fileName = '1';
    const promises = [Promise.resolve().then(() => __importStar(require(`./${fileName}.json`)))];
    fileName = '2';
    promises.push(Promise.resolve().then(() => __importStar(require(`./${fileName}.json`))));
    Promise.all(promises).then(results => console.log(results));
}
load();

🙁 Actual behavior

0 { '0': [Getter], default: [ 2 ] }
1 { '0': [Getter], default: [ 2 ] }

🙂 Expected behavior

0 { '0': [Getter], default: [ 1 ] }
1 { '0': [Getter], default: [ 2 ] }

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions