Skip to content

ts.transpileModule outputs commonjs with "module": "nodenext" and package.json "type": "module"Β #62734

@kyubisation

Description

@kyubisation

πŸ”Ž Search Terms

nodenext, commonjs, transpileModule, module, esm

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about nodenext

⏯ Playground Link

https://stackblitz.com/edit/wpaw3gcw?file=build.js

πŸ’» Code

index.ts

export function test() {
  console.log('test')
}

build.js

import * as ts from 'typescript';
import { basename, dirname, resolve } from 'node:path';
import { readFileSync } from 'node:fs';

const fileName = resolve('./index.ts');
const tsconfigPath = ts.findConfigFile(fileName, ts.sys.fileExists);
const { config, error } = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
if (error) {
  throw error;
}

const compilerOptions = ts.parseJsonConfigFileContent(
  config,
  ts.sys,
  dirname(tsconfigPath),
  undefined,
  basename(tsconfigPath)
).options;
const transpileResult = ts.transpileModule(readFileSync(fileName, 'utf8'), {
  compilerOptions,
  fileName,
});
// Should not contain require or exports
console.log(transpileResult);

tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "target": "ES2022",
    "module": "nodenext"
  }
}

πŸ™ Actual behavior

When transpiling a file with ts.transpileModule it is transpiled to commonjs even though "type": "module" is configured in the related package.json

πŸ™‚ Expected behavior

Transpiling a file with ts.transpileModule should transpile it to esm with "type": "module" configured in the related package.json

Additional information about the issue

From an initial analysis, this seems to be because in the transpile phase, the provided host cannot read the package.json, as the fileExists from the host will return false for an existing package.json.

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