ts2esm icon indicating copy to clipboard operation
ts2esm copied to clipboard

Fix absolute tsx imports not being converted to .js extensions

Open Copilot opened this issue 5 months ago • 0 comments

This PR fixes an issue where absolute imports (imports that don't start with . or ..) were not being converted to include .js extensions, while relative imports worked correctly.

The Problem

Previously, imports like this would not be converted:

import App from 'components/App';
// output =>
import App from 'components/App'; // (no change)

While relative imports worked fine:

import App from './components/App';
// output =>
import App from './components/App.js'; // ✅

Root Cause

The issue was in src/util/replaceModulePath.ts where the logic incorrectly classified absolute imports within the project as "node modules" imports. Any non-relative import containing a / that wasn't a path alias was assumed to be from node_modules, causing the tool to look for files in the wrong location.

The Solution

Modified the createReplacementPath function to:

  1. Properly handle absolute imports: Added logic to detect absolute imports within the project (non-relative imports that aren't path aliases)

  2. Support TypeScript's baseUrl: Use the TypeScript compiler's baseUrl configuration to correctly resolve absolute imports relative to the configured base directory

  3. Maintain fallback behavior: If a file isn't found as a project absolute import, fall back to checking node_modules to preserve existing functionality

Changes Made

  • Enhanced import classification logic to distinguish between project absolute imports and node_modules imports
  • Added support for baseUrl compiler option resolution
  • Added comprehensive test cases covering absolute import scenarios
  • All existing functionality and tests remain unchanged

Examples

The fix now correctly converts absolute imports in various configurations:

With baseUrl: "src":

// Before
import App from 'components/App';
import Utils from 'utils/helper';

// After  
import App from 'components/App.js';
import Utils from 'utils/helper.js';

With baseUrl: ".":

// Before
import App from 'components/App';

// After
import App from 'components/App.js';

Node modules imports remain unchanged:

import lodash from 'lodash'; // ✅ No conversion (correct)

Fixes #126.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot avatar Aug 09 '25 16:08 Copilot