Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ dist/
lerna-debug.log
node_modules/
npm-debug.log*

# Fake packages used as test fixtures
!src/test/fixtures/*/node_modules/
4 changes: 4 additions & 0 deletions src/converter/convertFile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ describe('convertFile', () => {
await testFileConversion('dynamic-imports');
});

it('adds file extensions to package imports only when needed to resolve as ESM', async () => {
await testFileConversion('package-exports');
});

it('handles index files referenced with a trailing slash', async () => {
await testFileConversion('trailing-slash');
});
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions src/test/fixtures/package-exports/src/main.snap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Legacy package without "exports" gets file extensions
import omit from 'legacy/omit.js';
import dir from 'legacy/dir/index.js';
// Package with "exports" stays untouched
import sub from 'modern/sub';
// Package root stays untouched
import pkg from '@scope/pkg';

console.log(omit, dir, sub, pkg);
9 changes: 9 additions & 0 deletions src/test/fixtures/package-exports/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Legacy package without "exports" gets file extensions
import omit from 'legacy/omit';
import dir from 'legacy/dir';
// Package with "exports" stays untouched
import sub from 'modern/sub';
// Package root stays untouched
import pkg from '@scope/pkg';

console.log(omit, dir, sub, pkg);
11 changes: 11 additions & 0 deletions src/test/fixtures/package-exports/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"module": "Node16",
"skipLibCheck": true,
"strict": true,
"target": "es2016"
},
"include": ["src"]
}
8 changes: 0 additions & 8 deletions src/util/PathUtil.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import path from 'node:path';
import fs from 'node:fs';
import type {ModuleInfo} from '../parser/InfoParser.js';

/**
Expand Down Expand Up @@ -55,10 +54,3 @@ export function hasRelativePath(path: string) {
}
return path.startsWith('./') || path.startsWith('../');
}

export function isNodeModuleRoot(directory: string): boolean {
const isInNodeModules = directory.includes(`node_modules${path.sep}`);
const packageJsonPath = path.join(directory, 'package.json');
const packageJsonExists = fs.existsSync(packageJsonPath);
return isInNodeModules && packageJsonExists;
}
54 changes: 43 additions & 11 deletions src/util/replaceModulePath.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {SourceFile, StringLiteral} from 'ts-morph';
import {SourceFile, StringLiteral, ts} from 'ts-morph';
import {ModuleInfo, parseInfo} from '../parser/InfoParser.js';
import {ProjectUtil} from './ProjectUtil.js';
import {toImport, toImportAttribute} from '../converter/ImportConverter.js';
import {getNormalizedPath, isNodeModuleRoot} from './PathUtil.js';
import {getNormalizedPath} from './PathUtil.js';
import path from 'node:path';
import {PathFinder} from './PathFinder.js';

Expand Down Expand Up @@ -49,24 +49,56 @@ function createReplacementPath({
return toImportAttribute(info);
}

if (isNodeModulesPath) {
return createPackageImportPath(info);
}

// If an import does not have a file extension or isn't an extension recognized here and can't be found locally (perhaps
// file had . in name), try to find a matching file by traversing through all valid TypeScript source file extensions.
let baseFilePath = comesFromPathAlias
const baseFilePath = comesFromPathAlias
? getNormalizedPath(projectDirectory, info, paths)
: path.join(info.directory, info.normalized);
if (isNodeModulesPath) {
baseFilePath = path.join(projectDirectory, 'node_modules', info.normalized);
}

const foundPath = PathFinder.findPath(baseFilePath, info.extension);
if (foundPath) {
// TODO: Write test case for this condition, mock "path" and "fs" calls if necessary
if (foundPath.extension === '/index.js' && isNodeModuleRoot(baseFilePath)) {
// @fixes https://github.com/bennycode/ts2esm/issues/81#issuecomment-2437503011
return null;
}
return toImport({...info, extension: foundPath.extension});
}
}
return null;
}

const ESM_RESOLUTION_OPTIONS: ts.CompilerOptions = {
allowJs: true,
module: ts.ModuleKind.NodeNext,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
};

// Resolves a specifier the way Node.js resolves it from an ES module, which respects "exports" in package.json
function resolvesAsESM(specifier: string, containingFile: string) {
const {resolvedModule} = ts.resolveModuleName(
specifier,
containingFile,
ESM_RESOLUTION_OPTIONS,
ts.sys,
undefined,
undefined,
ts.ModuleKind.ESNext
);
return !!resolvedModule;
}

// Imports from packages only get an extension when they don't resolve as written but do with the extension.
// This keeps imports of packages with "exports" (i.e. "firebase-functions/v1/https") untouched,
// while legacy packages (i.e. "lodash/omit") become "lodash/omit.js".
// @see https://github.com/bennycode/ts2esm/issues/128
function createPackageImportPath(info: ModuleInfo) {
if (resolvesAsESM(info.normalized, info.sourceFilePath)) {
return null;
}
for (const extension of ['.js', '/index.js']) {
if (resolvesAsESM(`${info.normalized}${extension}`, info.sourceFilePath)) {
return toImport({...info, extension});
}
}
return null;
}
Loading